apcore mcp防锈
apcore的自动MCP服务器和OpenAI工具桥(Rust版)。
apcore mcp 转动任何 apcore-将项目转化为MCP服务器和OpenAI工具提供商 零代码更改 您现有的项目。
┌──────────────────┐
│ axum-apcore │ ← your existing apcore project (unchanged)
│ project │
└────────┬─────────┘
│ extensions directory
▼
┌──────────────────┐
│ apcore-mcp-rust │ ← just install & point to extensions dir
└───┬──────────┬───┘
│ │
▼ ▼
MCP OpenAI
Server Tools设计理念
- 零入侵 --您的apcore项目不需要更改代码,不需要导入,也不需要依赖apcore mcp
- 零配置 --指向扩展目录,所有内容都会自动发现
- 纯适配器 --apcore mcp从apcore注册表中读取;它永远不会修改你的模块
- 适用于任何apcore项目 --如果它使用apcore模块注册表,apcore mcp可以为其提供服务
文档
有关完整文档,包括快速入门指南,请访问: ****
安装
作为一个图书馆
cargo add apcore-mcp作为CLI工具
cargo install apcore-mcp需要Rust 1.75+和 apcore >= 0.21.0 + apcore-toolkit >= 0.6.0.
快速开始
零代码方法(CLI)
如果你已经有一个基于apcore的带有扩展目录的项目,只需运行:
apcore-mcp --extensions-dir /path/to/your/extensions所有模块都是自动发现的,并作为MCP工具公开。不需要代码。
编程方法(Rust API)
这 APCoreMCP 构建器是推荐的入口点——一个对象,所有功能:
use std::sync::Arc;
use apcore::config::Config;
use apcore::executor::Executor;
use apcore::registry::registry::Registry;
use apcore_mcp::APCoreMCP;
fn main() -> Result> {
// 1. Create a registry and register your modules.
let registry = Registry::new();
// registry.register("my.tool", Box::new(MyModule), descriptor)?;
// 2. Wrap it in an Executor — APCoreMCP requires an executor backend.
let executor = Arc::new(Executor::new(registry, Config::default()));
// 3. Build and serve.
let mcp = APCoreMCP::builder()
.backend(executor)
.name("my-server")
.transport("streamable-http")
.port(8000)
.build()?;
// serve() is synchronous and blocks. It spawns its own Tokio runtime;
// do NOT call it from inside an active runtime (use async_serve() for
// embedded use, see API Overview below).
mcp.serve()?;
Ok(())
}后端注释(v0.15.0): Rust SDKBackendSource::Executor是 功能路径。BackendSource::ExtensionsDir(字符串路径)和BackendSource::Registry是当前返回a的保留变体BackendResolution错误来自build()--将注册表包装在Executor首先,如上所示。
Function-based API (still supported)
use apcore_mcp::{serve, to_openai_tools, ServeConfig, OpenAIToolsConfig};
// Pass an Arc as the backend (same constraint as the builder API).
serve(executor.clone(), ServeConfig::default())?;
let tools = to_openai_tools(executor, OpenAIToolsConfig::default())?;与现有项目集成
典型apcore项目结构
your-project/
├── extensions/ ← modules live here
│ ├── image_resize/
│ ├── text_translate/
│ └── ...
├── src/main.rs ← your existing code (untouched)
└── ...添加MCP支持
您的项目没有更改。只需在它旁边运行apcore mcp:
# Install (one time)
cargo install apcore-mcp
# Run
apcore-mcp --extensions-dir ./extensions您现有的应用程序继续像以前一样工作。apcore-mcp作为一个单独的进程运行,从同一个扩展目录读取。
添加OpenAI工具支持
对于OpenAI集成,需要一个精简的脚本,但仍然 不对现有模块进行更改:
use apcore_mcp::{to_openai_tools, OpenAIToolsConfig};
let tools = to_openai_tools("./extensions", OpenAIToolsConfig {
strict: true,
..Default::default()
})?;
// Use with the OpenAI APIMCP客户端配置
克劳德桌面版
添加 ~/Library/Application Support/Claude/claude_desktop_config.json (macOS)或 %APPDATA%\Claude\claude_desktop_config.json (Windows):
{
"mcpServers": {
"apcore": {
"command": "apcore-mcp",
"args": ["--extensions-dir", "/path/to/your/extensions"]
}
}
}克劳德代码
添加 .mcp.json 在项目根目录中:
{
"mcpServers": {
"apcore": {
"command": "apcore-mcp",
"args": ["--extensions-dir", "./extensions"]
}
}
}光标
添加 .cursor/mcp.json 在项目根目录中:
{
"mcpServers": {
"apcore": {
"command": "apcore-mcp",
"args": ["--extensions-dir", "./extensions"]
}
}
}远程HTTP访问
apcore-mcp --extensions-dir ./extensions \
--transport streamable-http \
--host 0.0.0.0 \
--port 9000将任何MCP客户端连接到 http://your-host:9000/mcp.
CLI参考
apcore-mcp --extensions-dir PATH [OPTIONS]| 选项 | 默认值 | 描述 |
|---|---|---|
--extensions-dir | *(必填)* | apcore扩展目录的路径 |
--transport | stdio | 运输: stdio, streamable-http,或 sse |
--host | 127.0.0.1 | 基于HTTP的传输主机 |
--port | 8000 | 基于HTTP的传输端口(1-65535) |
--name | apcore-mcp | MCP服务器名称(最多255个字符) |
--version | 包版本 | MCP服务器版本字符串 |
--log-level | INFO | 日志记录: DEBUG, INFO, WARNING, ERROR |
--explorer | off | 启用基于浏览器的工具资源管理器UI(仅限HTTP) |
--explorer-prefix | /explorer | 资源管理器UI的URL前缀 |
--allow-execute | off | 允许从资源管理器UI执行工具 |
--jwt-secret | -- | 承载令牌身份验证的JWT密钥(仅限HTTP) |
--jwt-key-file | -- | JWT验证的PEM密钥文件路径(例如RS256公钥) |
--jwt-algorithm | HS256 | JWT签名算法 |
--jwt-audience | -- | 预计JWT观众人数 |
--jwt-issuer | -- | 预计JWT发行人索赔 |
--jwt-require-auth | on | 需要有效令牌;使用 --no-jwt-require-auth 对于许可模式 |
--exempt-paths | -- | 逗号分隔的路径免于身份验证(例如。 /health,/metrics) |
--approval | off | 审批处理人: elicit, auto-approve, always-deny,或 off |
JWT密钥解析优先级: --jwt-key-file > --jwt-secret > APCORE_JWT_SECRET 环境变量。
退出代码: 0 正常, 1 无效参数, 2 启动失败。
Rust API参考
APCoreMCP (推荐)
统一入口点——配置一次,随处使用:
use apcore_mcp::APCoreMCP;
let mcp = APCoreMCP::builder()
.backend(executor) // Arc (the functional backend in v0.15.0)
.name("apcore-mcp") // server name
.version("1.0.0") // defaults to crate version
.tags(vec!["public".into()]) // filter modules by tags
.prefix("image") // filter modules by ID prefix
.transport("streamable-http") // "stdio" | "streamable-http" | "sse"
.host("127.0.0.1") // host for HTTP transports
.port(8000) // port for HTTP transports
.validate_inputs(true) // validate inputs against schemas
.authenticator(auth) // Authenticator for JWT/token auth (HTTP only)
.metrics_collector(collector) // MetricsExporter for /metrics endpoint
.output_formatter(formatter) // custom result formatting
.approval_handler(handler) // approval handler for runtime approval
.build()?;
// Launch as MCP server (synchronous, blocking; spawns its own Tokio runtime).
// Use `serve_with_options(ServeOptions { ... })` to pass on_startup/on_shutdown
// hooks, the explorer config, or `dynamic = true`.
mcp.serve()?;
// Export as OpenAI tools.
// The method takes (embed_annotations, strict) as positional booleans;
// use named-arg-style locals so the call reads consistently with the
// OpenAIToolsConfig form shown later in this guide.
let embed_annotations = false;
let strict = true;
let tools = mcp.to_openai_tools(embed_annotations, strict)?;
// Inspect
let tool_names = mcp.tools(); // list of module IDs
let registry = mcp.registry(); // underlying Registry
let executor = mcp.executor(); // underlying Executorserve() (基于功能)
use apcore_mcp::{serve, ServeConfig};
use std::sync::Arc;
// As noted in the builder caveat above, BackendSource::ExtensionsDir
// (string path) currently returns a BackendResolution error. Build an
// Executor first and pass it as the backend.
let registry: Arc = /* load extensions, e.g. via apcore::load_extensions("./extensions")? */;
let executor: Arc = Arc::new(apcore::Executor::new(registry, apcore::Config::default()));
serve(executor, ServeConfig {
transport: "streamable-http".into(),
host: "127.0.0.1".into(),
port: 8000,
name: "apcore-mcp".into(),
explorer: true,
allow_execute: true,
..Default::default()
})?;async_serve()
将MCP服务器嵌入到更大的应用程序中(例如与其他服务共同托管):
use apcore_mcp::{AsyncServeOptions, ExplorerOptions};
let app = mcp.async_serve(AsyncServeOptions {
// explorer is an ExplorerOptions struct, not a bool — set the
// inner `explorer: true` flag to mount the Tool Explorer UI.
explorer: ExplorerOptions {
explorer: true,
..Default::default()
},
..Default::default()
}).await?;
// Mount `app` (an axum::Router) into your own axum Router工具资源管理器
当 explorer.explorer = true 通过 ServeOptions,基于浏览器的工具资源管理器UI安装在HTTP传输上。它提供了一个交互式页面,用于浏览工具模式和测试工具执行。
use apcore_mcp::{ExplorerOptions, ServeOptions};
mcp.serve_with_options(ServeOptions {
explorer: ExplorerOptions {
explorer: true,
allow_execute: true,
..Default::default()
},
..Default::default()
})?;
// Open http://127.0.0.1:8000/explorer/ in a browser终点:
| 端点 | 描述 |
|---|---|
GET /explorer/ | 交互式HTML页面(自包含,无外部依赖) |
GET /explorer/tools | 包含名称、描述和注释的所有工具的JSON数组 |
GET /explorer/tools/ | 带有inputSchema的完整工具详细信息 |
POST /explorer/tools//call | 执行工具(需要 allow_execute=true) |
- 仅限HTTP传输 (
streamable-http,sse).默默地忽略了stdio. - 默认情况下禁用执行 --set
allow_execute=true启用Try it。 - 自定义前缀 --使用
explorer_prefix="/browse"以不同的路径安装。
JWT身份验证
HTTP传输的可选承载令牌身份验证。支持对称(HS256)和非对称(RS256)算法。
use apcore_mcp::JWTAuthenticator;
let auth = JWTAuthenticator::new("my-secret", None, None, None, None, None, None);
let mcp = APCoreMCP::builder()
.backend(executor) // Arc — see Quick Start for setup
.transport("streamable-http")
.authenticator(auth)
.build()?;允许模式 --允许未经身份验证的访问(身份为 None 当没有提供令牌时):
let auth = JWTAuthenticator::new("my-secret", None, None, None, None, None, Some(false));路径豁免 --通过CLI绕过特定路径的身份验证:
apcore-mcp --extensions-dir ./extensions --jwt-secret my-secret --exempt-paths /health,/metrics审批机制
工具执行的可选运行时批准。将MCP启发与apcore的审批系统联系起来。
use apcore_mcp::ElicitationApprovalHandler;
let handler = ElicitationApprovalHandler::new(None);
let mcp = APCoreMCP::builder()
.backend(executor) // Arc — see Quick Start for setup
.approval_handler(Arc::new(handler))
.build()?;内置处理程序:
| 处理程序 | 描述 |
|---|---|
ElicitationApprovalHandler | 通过诱导提示MCP客户端进行用户确认 |
AutoApproveHandler | 自动批准所有请求(仅限开发/测试) |
AlwaysDenyHandler | 拒绝所有请求(强制执行) |
CLI用法:
apcore-mcp --extensions-dir ./extensions --approval elicit输出格式化
默认情况下,工具执行结果被序列化为JSON。您可以通过传递 output_formatter 转换a的闭包 serde_json::Value 变成一根绳子。
use apcore_mcp::APCoreMCP;
let formatter = Box::new(|val: &serde_json::Value| -> Result> {
Ok(serde_json::to_string_pretty(val)?)
});
let mcp = APCoreMCP::builder()
.backend(executor) // Arc — see Quick Start for setup
.output_formatter(formatter)
.build()?;这 output_formatter 也可在 ExecutionRouter 直接。
扩展助手
模块可以在执行过程中通过MCP协议回调报告进度并请求用户输入。当在MCP上下文之外调用时,这两个助手都不会优雅地执行操作。
use apcore_mcp::{report_progress, elicit};
// Inside a module's execute():
report_progress(&context, progress_cb.as_ref(), 50.0, Some(100.0), Some("Halfway done")).await;
let result = elicit(&context, elicit_cb.as_ref(), "Confirm deletion?", Some(&schema)).await;
if let Some(r) = result {
if r.action == ElicitAction::Accept {
// proceed
}
}/metrics 普罗米修斯端点
当 metrics_collector 提供,a /metrics HTTP端点被公开,以Prometheus文本公开格式返回指标。
- 仅适用于基于HTTP的传输 (
streamable-http,sse).不适用于stdio运输。 - 返回Prometheus文本格式 与内容类型
text/plain; version=0.0.4; charset=utf-8. - 返回404 当否
metrics_collector已配置。
to_openai_tools()
use apcore_mcp::{to_openai_tools, OpenAIToolsConfig};
use std::sync::Arc;
// Same backend constraint as serve(): pass an Arc, not a
// path string (BackendSource::ExtensionsDir currently errors out).
let registry: Arc = /* load extensions, e.g. via apcore::load_extensions("./extensions")? */;
let executor: Arc = Arc::new(apcore::Executor::new(registry, apcore::Config::default()));
let tools = to_openai_tools(executor, OpenAIToolsConfig {
embed_annotations: false, // append annotation hints to descriptions
strict: true, // OpenAI Structured Outputs strict mode
tags: Some(vec!["image".into()]), // filter by tags
prefix: None, // filter by module ID prefix
})?;严格模式 (strict: true):组 additionalProperties: false,使所有属性都是必需的(可选属性可以为空),删除默认值。
注释嵌入 (embed_annotations: true):附加 [Annotations: read_only, idempotent] 描述。
过滤: tags 或 prefix 以暴露模块的子集。
特性
- 自动发现 --自动找到并公开扩展目录中的所有模块
- 显示叠加 —
metadata["display"]["mcp"]控制每个模块的MCP工具名称、描述和指导(§5.13) - Markdown工具说明 (
MCPServerFactory::with_rich_description(true),v0.15+)--渲染Tool.description作为规范的apcore工具包Markdown,LLM每个令牌获得更多与决策相关的信号;由...支持apcore_toolkit::format_module(ModuleStyle::Markdown). - 模块预览元工具 (
__apcore_module_preview,v0.15+)--驱动器executor.validate()在不执行模块的情况下预测状态变化(apcore PROTOCOL_SPEC§5.6)。退货{valid, requires_approval, predicted_changes, checks}因此,人工智能编排者在调用之前可以问“会发生什么变化?”。 - 三次运输 --stdio(默认,用于桌面客户端)、流式HTTP和SSE
- JWT身份验证 --HTTP传输的可选承载令牌身份验证
JWTAuthenticator、许可模式、PEM密钥文件支持和环境变量回退 - 审批机制 --通过MCP启发、自动批准或始终拒绝处理程序进行运行时批准
- AI指导 --错误响应包括
retryable,ai_guidance,user_fixable,以及suggestion代理消费字段 - AI意图元数据 --工具描述丰富
x-when-to-use,x-when-not-to-use,x-common-mistakes,x-workflow-hints来自模块元数据 - 扩展助手 --模块可以调用
report_progress()和elicit()在执行过程中,用于MCP进度报告和用户输入 - 注释映射 --apcore注释(只读、破坏性、幂等)映射到MCP工具注释
- 模式转换 --JSON模式
$ref/$defsOpenAI结构化输出的内联严格模式 - 错误清理 --ACL错误和内部错误被清除;堆栈痕迹永远不会泄漏
- 动态注册 --在运行时注册/未注册的模块会立即反映出来
- 双输出 --同一注册表为MCP服务器和OpenAI工具定义提供支持
- 工具资源管理器 --基于浏览器的UI,用于交互式浏览模式和测试工具
- 配置总线集成 --注册a
mcp带有apcore配置总线的命名空间;通过统一配置传输、主机、端口等apcore.yaml或APCORE_MCP_*环境变量 - 格式化程序注册表错误 --注册一个特定于MCP的错误格式化程序,用于全生态系统一致的错误处理
配置总线集成
apcore mcp注册了一个 mcp 使用apcore配置总线的命名空间 APCoreMCPBuilder::build().MCP设置可以与其他apcore配置一起使用 apcore.yaml:
apcore:
version: "1.0.0"
mcp:
transport: streamable-http
host: 0.0.0.0
port: 9000
explorer: true
require_auth: false环境变量重写使用 APCORE_MCP_ 前缀:
APCORE_MCP_TRANSPORT=streamable-http
APCORE_MCP_PORT=9000
APCORE_MCP_EXPLORER=true默认值: transport=stdio, host=127.0.0.1, port=8000, explorer=false, require_auth=true.
命名空间、前缀和默认值也可以作为可导入常量使用:
use apcore_mcp::{MCP_NAMESPACE, MCP_ENV_PREFIX, mcp_defaults, register_mcp_namespace};运作原理
映射:apcore到MCP
| apcore | MCP |
|---|---|
module_id | 工具名称 |
description | 工具说明 |
input_schema | inputSchema |
annotations.readonly | ToolAnnotations.readOnlyHint |
annotations.destructive | ToolAnnotations.destructiveHint |
annotations.idempotent | ToolAnnotations.idempotentHint |
annotations.open_world | ToolAnnotations.openWorldHint |
映射:apcore到OpenAI工具
| apcore | OpenAI |
|---|---|
module_id (image.resize) | name (image-resize) |
description | description |
input_schema | parameters |
带有点的模块ID被标准化为破折号,以实现OpenAI兼容性(双射映射)。
建筑
Your apcore project (unchanged)
│
│ extensions directory
▼
apcore-mcp-rust (separate process / library call)
│
├── MCP Server path
│ SchemaConverter + AnnotationMapper
│ → MCPServerFactory → ExecutionRouter → TransportManager
│
└── OpenAI Tools path
SchemaConverter + AnnotationMapper + IDNormalizer
→ OpenAIConverter → Vec发展
git clone https://github.com/aiperceivable/apcore-mcp-rust.git
cd apcore-mcp-rust
make setup # install toolchain + pre-commit hook
make check # run all checks
cargo test # comprehensive test suite spanning unit + integration tests across server, auth, adapters, converters, helpers, async-task, explorer layers (~821 tests)常用命令
| 命令 | 描述 |
|---|---|
make check | 运行所有检查(格式、lint、字符、测试) |
make test | 运行所有测试 |
make lint | 运行Clippy时,警告为错误 |
make fmt | 自动格式化代码 |
make clean | 清理构建工件 |
许可证
阿帕奇-2.0
