apcore mcp
自动MCP服务器和OpenAI工具桥 apcore.
将apcore模块注册表转换为 模型上下文协议(MCP) 工具定义和 OpenAI兼容函数调用 格式——不需要样板。
特性
- MCP服务器 --通过stdio、Streamable HTTP或SSE将apcore模块作为MCP工具公开
- OpenAI工具 --将模块转换为具有严格模式支持的OpenAI函数调用格式
- Markdown工具说明 (
richDescription: true,v0.15+)--渲染Tool.descriptionOpenAIfunction.description作为规范的apcore工具包Markdown,LLM每个令牌获得更多与决策相关的信号。需要apcore-toolkit(宣布为optionalDependencies)以及await MCPServerFactory.prepare()在启动时。 - 模块预览元工具 (
__apcore_module_preview,v0.15+)--驱动器executor.validate()在不执行模块的情况下预测状态变化(apcore PROTOCOL_SPEC§5.6)。退货{valid, requires_approval, predicted_changes, checks}因此,人工智能编排者在调用之前可以问“会发生什么变化?”。 - 架构转换 --内联
$defs/$ref从Pydantic生成的JSON模式 - 注释映射 --将模块注释映射到MCP提示和OpenAI描述后缀
- 审批机制 --针对敏感工具执行的内置基于启发的审批流
- 错误映射 --清除内部错误,以获得面向客户的安全响应
- 动态注册 --在运行时监听注册表更改并更新工具
- 工具资源管理器 --基于浏览器的用户界面,用于交互式浏览模式和测试工具
- 命令行界面 --从命令行启动MCP服务器
- 配置总线集成 --注册一个
mcp带有apcore配置总线的命名空间;通过统一配置apcore.yaml或APCORE_MCP_*环境变量 - 格式化程序注册表错误 --注册特定于MCP的错误格式化程序,以实现生态系统范围内一致的错误处理
文档
有关完整文档,包括Python和TypeScript的快速入门指南,请访问: ****
需求
- Node.js>=18.0.0
apcore-js >= 0.21.1- 可选:
apcore-toolkit >= 0.6.1用于Markdown渲染的工具描述(声明如下optionalDependencies).
安装
npm install apcore-mcpapcore-js 作为直接依赖项包含在内,无需单独安装。
快速开始
程序化API
import { serve, toOpenaiTools } from "apcore-mcp";
// Launch MCP server over stdio
await serve(executor);
// Launch over Streamable HTTP
await serve(executor, {
transport: "streamable-http",
host: "127.0.0.1",
port: 8000,
});
// Export OpenAI tool definitions
const tools = toOpenaiTools(registry, {
embedAnnotations: true,
strict: true,
});命令行界面
# stdio (default)
npx apcore-mcp --extensions-dir ./extensions
# Streamable HTTP
npx apcore-mcp --extensions-dir ./extensions --transport streamable-http --port 8000
# SSE
npx apcore-mcp --extensions-dir ./extensions --transport sse --port 8000CLI参数
| 参数 | 默认值 | 描述 |
|---|---|---|
--extensions-dir | *(必填)* | apcore扩展目录的路径 |
--transport | stdio | stdio, streamable-http,或 sse |
--host | 127.0.0.1 | HTTP传输主机 |
--port | 8000 | HTTP传输端口(1-65535) |
--name | apcore-mcp | MCP服务器名称 |
--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密钥 |
--jwt-key-file | -- | JWT验证的PEM密钥文件路径(RS256/ES256) |
--jwt-algorithm | HS256 | JWT算法 |
--jwt-audience | -- | 预计JWT观众人数 |
--jwt-issuer | -- | 预计JWT发行人索赔 |
--jwt-require-auth | true | 需要身份验证(使用 --jwt-permissive 覆盖并允许未经身份验证的请求) |
--jwt-permissive | false | 许可模式:允许未经身份验证的请求(覆盖 --jwt-require-auth) |
--exempt-paths | /health,/metrics,/usage | 逗号分隔的路径免于身份验证 |
--output-format | json | 内置输出格式: json, csv,或 jsonl |
JWT密钥解析优先级: --jwt-key-file > --jwt-secret > APCORE_JWT_SECRET 环境变量。
MCP客户端配置
克劳德桌面
添加 ~/Library/Application Support/Claude/claude_desktop_config.json (macOS)或 %APPDATA%\Claude\claude_desktop_config.json (Windows):
{
"mcpServers": {
"apcore": {
"command": "npx",
"args": ["apcore-mcp", "--extensions-dir", "/path/to/your/extensions"]
}
}
}克劳德代码
添加 .mcp.json 在项目根目录中:
{
"mcpServers": {
"apcore": {
"command": "npx",
"args": ["apcore-mcp", "--extensions-dir", "./extensions"]
}
}
}光标
添加 .cursor/mcp.json 在项目根目录中:
{
"mcpServers": {
"apcore": {
"command": "npx",
"args": ["apcore-mcp", "--extensions-dir", "./extensions"]
}
}
}远程HTTP访问
npx apcore-mcp --extensions-dir ./extensions \
--transport streamable-http \
--host 0.0.0.0 \
--port 9000将任何MCP客户端连接到 http://your-host:9000/mcp.
API 参考
编程API—— APCoreMCP 类
这 APCoreMCP 类是推荐的OOP入口点。它捆绑了一个统一的配置对象,懒惰的后端解析(路径/ Registry / Executor),并暴露 serve / asyncServe / toOpenaiTools 作为实例方法,您只需配置一次即可在任何地方使用。
import { APCoreMCP } from "apcore-mcp";
// 1. Point at an extensions directory (lazy discovery on first use)
const mcp = new APCoreMCP("./extensions", {
name: "my-server",
tags: ["public"],
observability: true,
});
// 2. Launch as MCP server (blocks until shutdown)
await mcp.serve({ transport: "streamable-http", port: 8000, explorer: true });
// 3. Or export OpenAI tool definitions
const tools = mcp.toOpenaiTools({ strict: true });
// 4. Or embed into an existing HTTP server
const app = await mcp.asyncServe({ explorer: true });
// app.handler is a Node.js request handler; call app.close() on shutdown
// 5. Or pass an existing Registry / Executor
import { Registry } from "apcore-js";
const registry = new Registry({ extensionsDir: "./extensions" });
await registry.discover();
const mcp2 = new APCoreMCP(registry, { name: "my-server", tags: ["public"] });构造函数
new APCoreMCP(
extensionsDirOrBackend: string | Registry | Executor,
options?: APCoreMCPOptions,
);第一个参数要么是apcore扩展目录的路径(发现推迟到第一次使用),要么是现有的 Registry / Executor 例子
APCoreMCPOptions 领域
name--MCP服务器名称。违约:"apcore-mcp"version--MCP服务器版本。默认值:包版本tags--按标签列表过滤模块prefix--按ID前缀过滤模块logLevel--最低日志级别(DEBUG|INFO|WARNING|ERROR|CRITICAL)validateInputs--根据模式验证输入。违约:falsemetricsCollector—MetricsExporter或true自动实例化observability--启用完整的度量+使用可观察性堆栈async—boolean | { enabled?, maxConcurrent?, maxTasks? }异步任务桥(F-043)authenticator--可选Authenticator(仅限HTTP传输)requireAuth--如果true(默认),使用401拒绝未经身份验证的请求exemptPaths--免于身份验证的路径approvalHandler--传递给执行者的可选审批处理程序outputFormatter--用于格式化工具执行结果的自定义函数middleware--apcore数组Middleware通过安装executor.use()acl--可选apcoreACL通过安装实例executor.setAcl()
属性
.registry--底层apcoreRegistry(首次访问时解决).executor--底层apcoreExecutor(填充后serve()/asyncServe()).tools--将作为工具公开的已发现模块ID列表(荣誉tags/prefix)
方法
.serve(options?)--启动MCP服务器。接受APCoreMCPServeOptions:transport,host,port,onStartup,onShutdown,explorer,explorerPrefix,allowExecute,explorerTitle,explorerProjectName,explorerProjectUrl构造函数级别的选项(身份验证、可观察性、中间件、acl、异步等)会自动应用。.asyncServe(options?)--构建一个可嵌入的Node.js HTTP请求处理程序。接受APCoreMCPAsyncServeOptions:explorer,explorerPrefix,allowExecute,explorerTitle,explorerProjectName,explorerProjectUrl,endpoint.退货{ handler, close }..toOpenaiTools(options?)--将模块导出为与OpenAI兼容的工具定义。接受ToOpenaiToolsOptions:embedAnnotations,strict.tags/prefix从构造函数继承。
serve(registryOrExecutor, options?)
启动一个MCP服务器,将所有apcore模块作为工具公开。
function serve(
registryOrExecutor: Registry | Executor,
options?: {
// Transport
transport?: "stdio" | "streamable-http" | "sse";
host?: string;
port?: number;
// Identity
name?: string;
version?: string;
// Lifecycle
onStartup?: () => void | Promise;
onShutdown?: () => void | Promise;
// Module filtering / discovery
tags?: string[] | null;
prefix?: string | null;
dynamic?: boolean;
validateInputs?: boolean;
logLevel?: "DEBUG" | "INFO" | "WARNING" | "ERROR" | "CRITICAL";
// Async Task Bridge (F-043)
async?: boolean | { enabled?: boolean; maxConcurrent?: number; maxTasks?: number };
// Executor wiring
middleware?: unknown[];
acl?: unknown;
approvalHandler?: unknown;
strategy?: string;
// Observability (F-044)
metricsCollector?: MetricsExporter | boolean;
observability?: ObservabilityFlag;
trace?: boolean;
// Output handling
outputFormatter?: (result: Record) => string;
redactOutput?: boolean;
// Auth (HTTP transports only)
authenticator?: Authenticator;
requireAuth?: boolean;
exemptPaths?: string[];
// Tool Explorer UI
explorer?: boolean;
explorerPrefix?: string;
allowExecute?: boolean;
explorerTitle?: string;
explorerProjectName?: string;
explorerProjectUrl?: string;
// Adapter overrides (advanced — Extension Bridge)
schemaConverter?: SchemaConverter;
annotationMapper?: AnnotationMapper;
errorMapper?: ErrorMapper;
}
): Promise;选项参考:
*运输*
transport—"stdio"(默认),"streamable-http",或"sse"host--基于HTTP的传输的主机地址。违约:"127.0.0.1"port--用于基于HTTP的传输的端口。违约:8000
*身份*
name--MCP服务器名称。违约:"apcore-mcp"version--MCP服务器版本。默认值:包版本
*生命周期*
onStartup--服务器启动前调用异步回调onShutdown--服务器停止后(或发生错误时)调用异步回调
*模块过滤/发现*
tags--按标签列表过滤模块。违约:null(无过滤)prefix--按ID前缀过滤模块。违约:null(无过滤)dynamic--通过以下方式启用动态工具注册RegistryListener默认值:falsevalidateInputs--在分派之前根据模式验证输入。违约:falselogLevel--最低日志级别。禁止低于此级别的控制台方法
*异步任务桥(F-043)*
async--启用AsyncTaskBridge并__apcore_task_*元工具。通过false禁用,或{ maxConcurrent, maxTasks }用于细粒度调优。违约:true
*执行器接线*
middleware--apcore数组Middleware通过安装的实例executor.use().附加到Config Bus键下声明的任何中间件mcp.middlewareacl--可选apcoreACL通过安装实例executor.setAcl().呼叫者提供的ACL优先于mcp.acl配置总线入口approvalHandler--传递给执行者的可选审批处理程序(例如。ElicitationApprovalHandler)strategy--传递给执行者的执行策略名称(例如。"standard","internal")
*可观察性(F-044)*
metricsCollector—MetricsExporter实例,或true自动实例化apcore-jsMetricsCollector并安装MetricsMiddlewareobservability--启用完整的可观察性堆栈(度量+使用中间件)并公开/metrics+/usage端点trace--何时true,通过以下方式启用管道跟踪callWithTrace().添加_meta.trace非流媒体工具响应。违约:false
*输出句柄*
outputFormatter--自定义函数,用于格式化工具执行结果。当未定义时,结果将序列化为JSON.stringify(result)redactOutput--何时true(默认),通过apcore从工具输出中编辑敏感字段redactSensitive()格式化之前
*身份验证(仅限HTTP传输)*
authenticator—Authenticator请求身份验证实例requireAuth--如果true(默认),未经身份验证的请求将被401拒绝。设为false对于许可模式exemptPaths--免于身份验证的路径。违约:["/health", "/metrics"]
*工具资源管理器UI*
explorer--启用基于浏览器的工具资源管理器UI(仅限HTTP)。违约:falseexplorerPrefix--资源管理器的URL前缀。违约:"/explorer"allowExecute--允许从资源管理器UI执行工具。违约:falseexplorerTitle--工具资源管理器UI页面的自定义标题explorerProjectName--资源管理器UI页脚中显示的项目名称explorerProjectUrl--资源管理器UI页脚中显示的项目URL
*适配器超控(高级——扩展桥,F-042)*
schemaConverter--覆盖默认值SchemaConverter(自定义JSON模式严格性/方言)annotationMapper--覆盖默认值AnnotationMapper(自定义注释线格式)errorMapper--覆盖默认值ErrorMapper消费由ExecutionRouter
asyncServe(registryOrExecutor, options?)
将MCP服务器嵌入到更大的Node.js HTTP应用程序中。返回一个HTTP请求处理程序和一个用于生命周期管理的关闭函数。
import { asyncServe } from "apcore-mcp";
const { handler, close } = await asyncServe(executor, {
name: "apcore-mcp",
explorer: true,
allowExecute: true,
});
// Mount in a custom HTTP server
const server = http.createServer(handler);
server.listen(8000);
// Clean up when done
await close();接受与相同的选项 serve() 除了 transport, host, port, onStartup,以及 onShutdown.
输出格式化
默认情况下,工具执行结果序列化为JSON(JSON.stringify).您可以通过传递 outputFormat 名称或自定义 outputFormatter 功能。
内置格式 (要求 apcore-toolkit 0.7.0+):
// Via CLI
// npx apcore-mcp --extensions-dir ./extensions --output-format csv
// Via API
const mcp = new APCoreMCP("./extensions", { outputFormat: "csv" });支持 json, csv,以及 jsonl非表格数据优雅地回落到JSON。
工具资源管理器
当 explorer: true 传递给 serve(),基于浏览器的工具资源管理器UI安装在HTTP传输上。它提供了一个交互式页面,用于浏览工具模式和测试工具执行。
await serve(registry, {
transport: "streamable-http",
explorer: true,
allowExecute: true,
});
// 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 | 执行工具(需要 allowExecute: true) |
- 仅限HTTP传输 (
streamable-http,sse).默默地忽略了stdio. - 默认情况下禁用执行 --set
allowExecute: true启用Try it。 - 自定义前缀 --使用
explorerPrefix: "/browse"以不同的路径安装。 - 授权UI --Swagger UI风格的授权输入字段。粘贴承载令牌以验证工具执行请求。生成的cURL命令会自动包含Authorization标头。
JWT身份验证
apcore-mcp支持基于HTTP的传输的JWT承载令牌身份验证。
程序化使用
import { serve, JWTAuthenticator } from "apcore-mcp";
const authenticator = new JWTAuthenticator({
key: "your-secret-key",
algorithms: ["HS256"],
audience: "my-app",
issuer: "auth-service",
// Map custom claims to Identity fields
claimMapping: {
id: "sub",
type: "type",
roles: "roles",
attrs: ["email", "org"], // Extra claims → Identity.attrs
},
// Claims that must be present in the token (default: ["sub"])
requireClaims: ["sub", "email"],
// Set to false for permissive mode (allow unauthenticated requests)
requireAuth: true,
});
await serve(executor, {
transport: "streamable-http",
authenticator,
// Custom exempt paths (default: ["/health", "/metrics"])
exemptPaths: ["/health", "/metrics", "/status"],
});CLI标志
| 标志 | 默认值 | 描述 |
|---|---|---|
--jwt-secret | -- | 用于承载令牌身份验证的JWT密钥 |
--jwt-key-file | -- | JWT验证的PEM密钥文件路径 |
--jwt-algorithm | HS256 | JWT算法 |
--jwt-audience | -- | 预期观众人数 |
--jwt-issuer | -- | 预期发行人索赔 |
--jwt-require-auth | true | 需要身份验证。使用 --jwt-permissive 允许未经身份验证的请求 |
--jwt-permissive | false | 覆盖范围 --jwt-require-auth 并允许未经身份验证的请求 |
--exempt-paths | /health,/metrics,/usage | 逗号分隔的路径免于身份验证 |
JWT密钥解析优先级: --jwt-key-file > --jwt-secret > APCORE_JWT_SECRET 环境变量。
curl示例
# Authenticated request
curl -X POST http://localhost:8000/mcp \
-H "Content-Type: application/json" \
-H "Authorization: Bearer " \
-d '{"jsonrpc":"2.0","method":"tools/list","id":1}'
# Health check (always exempt)
curl http://localhost:8000/healthtoOpenaiTools(registryOrExecutor, options?)
将apcore模块导出为OpenAI兼容的工具定义。
function toOpenaiTools(
registryOrExecutor: Registry | Executor,
options?: {
embedAnnotations?: boolean;
strict?: boolean;
tags?: string[];
prefix?: string;
}
): OpenAIToolDef[];选项:
embedAnnotations--将注释元数据附加到工具描述中(默认值:false)strict--启用OpenAI严格模式:添加additionalProperties: false,使所有属性都是必需的,将可选属性包装为可以为null(默认值:false)tags--按标签过滤模块prefix--按ID前缀过滤模块
reportProgress(context, progress, total?, message?)
向MCP客户端报告执行进度。在MCP上下文之外调用时,没有静默操作(没有注入回调)。
import { reportProgress } from "apcore-mcp";
// Inside a module's execute() method:
await reportProgress(context, 5, 10, "Processing item 5 of 10");参数:
context--带有a的对象datadict(apcore上下文或BridgeContext)progress--当前进度值total--用于百分比计算的可选总计message--可选的人类可读进度消息
elicit(context, message, requestedSchema?)
通过启发协议向MCP客户端请求用户输入。退货 null 当在MCP上下文之外调用时。
import { elicit } from "apcore-mcp";
import type { ElicitResult } from "apcore-mcp";
// Inside a module's execute() method:
const result: ElicitResult | null = await elicit(
context,
"Are you sure you want to proceed?",
{
type: "object",
properties: {
confirmed: { type: "boolean", description: "Confirm action" },
},
required: ["confirmed"],
},
);
if (result?.action === "accept") {
// User confirmed
}参数:
context--带有a的对象datadict(apcore上下文或BridgeContext)message--要向用户显示的消息requestedSchema--描述预期输入的可选JSON模式
退货: ElicitResult 随着 action ("accept", "decline",或 "cancel")可选 content,或 null 如果不是在MCP上下文中。
配置总线集成
apcore mcp注册了一个 mcp 在以下情况下使用apcore配置总线的命名空间 serve() 或 asyncServe() 被称为。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.
命名空间、前缀和默认值也可以作为可导入常量使用:
import { MCP_NAMESPACE, MCP_ENV_PREFIX, MCP_DEFAULTS, registerMcpNamespace } from "apcore-mcp";发展
# Install dependencies
npm install
# Type check
npm run typecheck
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Build
npm run build
# Watch mode
npm run dev许可证
阿帕奇-2.0
