Skip to content

Commit acf0f71

Browse files
author
linyuan.yang
committed
MCP 改为原生 SDK
1 parent 44b5903 commit acf0f71

11 files changed

Lines changed: 574 additions & 346 deletions

File tree

‎packages/backend/sbot/src/Agent/GlobalAgentToolService.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { AgentToolService, GlobalLoggerService } from "scorpio.ai";
1+
import { AgentToolService, GlobalLoggerService, MCPTransport } from "scorpio.ai";
22
import { config } from "../Core/Config.js";
33
import { loadPrompt } from "../Core/PromptLoader.js";
44

@@ -77,9 +77,9 @@ export function initGlobalAgentToolService() {
7777
}, '查询/发消息/发文件 跨 channel 会话');
7878
globalAgentToolService.registerMcpServers({
7979
[BuiltinProvider.Exa]: {
80-
"type": "http",
81-
"url": "https://mcp.exa.ai/mcp",
82-
"description": "Exa 网络搜索",
80+
type: MCPTransport.Http,
81+
url: "https://mcp.exa.ai/mcp",
82+
description: "Exa 网络搜索",
8383
},
8484
})
8585
globalAgentToolService.registerMcpServers(config.getGlobalMcpServers());

‎packages/backend/scorpio.ai/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"dependencies": {
1111
"@agentclientprotocol/sdk": "^0.26.0",
1212
"@langchain/core": "catalog:",
13-
"@langchain/mcp-adapters": "^1.1.3",
13+
"@modelcontextprotocol/sdk": "catalog:",
1414
"better-sqlite3": "catalog:",
1515
"commander": "catalog:",
1616
"cron": "catalog:",

‎packages/backend/scorpio.ai/src/AgentTool/AgentToolService.ts‎

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { StructuredToolInterface } from "@langchain/core/tools";
1+
import { type AgentTool } from "scorpio.llm";
22
import { IAgentToolService, type ProviderResolveEntry } from "./IAgentToolService";
33
import { MCPServers } from "./MCPServerConfig";
44
import { ILoggerService } from "../Logger";
@@ -29,7 +29,7 @@ export class AgentToolService implements IAgentToolService {
2929
this.logger = loggerService?.getLogger("AgentToolService");
3030
}
3131

32-
registerToolFactory(name: string, factory: (params?: Record<string, any>) => Promise<StructuredToolInterface[]>, description?: string): void {
32+
registerToolFactory(name: string, factory: (params?: Record<string, any>) => Promise<AgentTool[]>, description?: string): void {
3333
this.providers.set(name, {
3434
factory: async (params) => ({ tools: await factory(params) }),
3535
description,
@@ -50,31 +50,25 @@ export class AgentToolService implements IAgentToolService {
5050
let resourceTemplates: MCPResourceTemplate[] | undefined;
5151

5252
try {
53-
prompts = await client.runOperation(async (c) => {
54-
const rc = await c.getClient(name);
55-
if (!rc) return undefined as MCPPrompt[] | undefined;
56-
return (await rc.listPrompts()).prompts as MCPPrompt[];
57-
});
53+
prompts = await client.runOperation(async (c) => (await c.listPrompts()).prompts as MCPPrompt[]);
5854
} catch {}
5955
try {
60-
resources = await client.runOperation(async (c) => (await c.listResources(name))[name]);
56+
resources = await client.runOperation(async (c) => (await c.listResources()).resources as MCPResource[]);
6157
} catch {}
6258
try {
63-
resourceTemplates = await client.runOperation(async (c) => (await c.listResourceTemplates(name))[name]);
59+
resourceTemplates = await client.runOperation(async (c) => (await c.listResourceTemplates()).resourceTemplates as MCPResourceTemplate[]);
6460
} catch {}
6561

6662
return {
6763
tools, prompts, resources, resourceTemplates,
6864
getPrompt: async (promptName: string, args?: Record<string, string>) => {
6965
return client.runOperation(async (c) => {
70-
const rc = await c.getClient(name);
71-
if (!rc) throw new Error(`MCP client for "${name}" not available`);
72-
const result = await rc.getPrompt({ name: promptName, arguments: args });
66+
const result = await c.getPrompt({ name: promptName, arguments: args });
7367
return result.messages as MCPPromptMessage[];
7468
});
7569
},
7670
readResource: async (uri: string) => {
77-
return client.runOperation(async (c) => c.readResource(name, uri));
71+
return client.runOperation(async (c) => (await c.readResource({ uri })).contents);
7872
},
7973
close: async () => { await client.close(); },
8074
};
@@ -85,9 +79,9 @@ export class AgentToolService implements IAgentToolService {
8579
}
8680
}
8781

88-
async getAllTools(): Promise<StructuredToolInterface[]> {
82+
async getAllTools(): Promise<AgentTool[]> {
8983
await this.loadAll();
90-
const result: StructuredToolInterface[] = [];
84+
const result: AgentTool[] = [];
9185
for (const caps of this.providerResults.values()) result.push(...caps.tools);
9286
return result;
9387
}

‎packages/backend/scorpio.ai/src/AgentTool/MCPServerConfig.ts‎

Lines changed: 61 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,64 @@
1-
import type { Connection } from "@langchain/mcp-adapters";
2-
31
/**
42
* MCP 服务器配置
5-
* 重新导出 @langchain/mcp-adapters 的 Connection 类型
3+
*
4+
* 原先 re-export @langchain/mcp-adapters 的 Connection 类型;迁移到原生
5+
* @modelcontextprotocol/sdk 后改为自建类型,字段与既有用户配置完全兼容
6+
* (type / transport 两种写法均接受,缺省时按结构推断:有 command → stdio,有 url → http)。
67
*
78
* 支持 stdio、http 两种传输方式:
89
*
910
* **Stdio 方式:**
1011
* - command: 要运行的可执行文件(如 node、npx、python 等)- 必需
11-
* - args: 传递给可执行文件的命令行参数
12+
* - args: 传递给可执行文件的命令行参数 - 必需
1213
* - env: 环境变量
1314
* - cwd: 工作目录
1415
* - stderr: stderr 处理方式(默认:inherit)
15-
* - restart: 进程重启配置
1616
*
1717
* **HTTP 方式:**
1818
* - url: 服务器 URL - 必需
1919
* - headers: 请求头(用于身份验证等)
20-
* - authProvider: OAuth 认证提供者
21-
* - reconnect: 重新连接配置
22-
* - automaticSSEFallback: 是否自动回退到 SSE
23-
*
24-
* **工具配置:**
25-
* - disabled: 禁用的工具列表(这些工具将不会被加载)
26-
* - defaultToolTimeout: 工具执行的默认超时时间(毫秒)
20+
* - automaticSSEFallback: streamable HTTP 连接失败(4xx)时是否自动回退到 SSE(默认:true)
21+
* - type/transport 为 MCPTransport.Sse 时直接走 SSE,不做 streamable HTTP 尝试
2722
*
28-
* **输出处理:**
29-
* - outputHandling: 工具输出的处理方式("content" | "artifact" | 对象)
23+
* **扩展字段:**
24+
* - name: 服务器名称
25+
* - description: Provider 描述
26+
* - enablePromptTools: 启用 prompts utility tools 生成(默认不启用)
27+
* - enableResourceTools: 启用 resources utility tools 生成(默认不启用)
28+
*/
29+
30+
/**
31+
* MCP 传输方式。枚举值为字符串,与既有 JSON 配置中的 type/transport 字段直接兼容。
3032
*/
31-
export type MCPServerConfig = Connection & {
33+
export enum MCPTransport {
34+
/** 本地子进程(command + args) */
35+
Stdio = "stdio",
36+
/** 远程 streamable HTTP(连接失败时可自动回退 SSE) */
37+
Http = "http",
38+
/** 远程 SSE(旧版传输协议) */
39+
Sse = "sse",
40+
}
41+
42+
export type MCPStdioConfig = {
43+
transport?: MCPTransport.Stdio;
44+
type?: MCPTransport.Stdio;
45+
command: string;
46+
args: string[];
47+
env?: Record<string, string>;
48+
cwd?: string;
49+
stderr?: "overlapped" | "pipe" | "ignore" | "inherit";
50+
};
51+
52+
export type MCPHttpConfig = {
53+
transport?: MCPTransport.Http | MCPTransport.Sse;
54+
type?: MCPTransport.Http | MCPTransport.Sse;
55+
url: string;
56+
headers?: Record<string, string>;
57+
/** streamable HTTP 连接失败(4xx)时自动回退到 SSE */
58+
automaticSSEFallback?: boolean;
59+
};
60+
61+
export type MCPServerConfig = (MCPStdioConfig | MCPHttpConfig) & {
3262
/** 服务器名称 - 扩展字段 */
3363
name?: string;
3464
/** Provider 描述 - 扩展字段 */
@@ -39,6 +69,22 @@ export type MCPServerConfig = Connection & {
3969
enableResourceTools?: boolean;
4070
};
4171

72+
/**
73+
* 判定配置是否为 stdio 传输(有 command 即视为 stdio,与 mcp-adapters 的推断一致)
74+
*/
75+
export function isStdioConfig(config: MCPServerConfig): config is MCPStdioConfig {
76+
const transport = (config as MCPStdioConfig).transport ?? (config as MCPStdioConfig).type;
77+
if (transport === MCPTransport.Stdio) return true;
78+
return typeof (config as MCPStdioConfig).command === "string";
79+
}
80+
81+
/**
82+
* 判定配置是否显式要求 SSE 传输
83+
*/
84+
export function isSseConfig(config: MCPHttpConfig): boolean {
85+
return config.transport === MCPTransport.Sse || config.type === MCPTransport.Sse;
86+
}
87+
4288
/**
4389
* MCP 服务器集合
4490
* Key 为服务器名称,Value 为服务器配置
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
/**
2+
* MCP 工具 inputSchema 的 JSON Schema 预处理
3+
*
4+
* 移植自 @langchain/mcp-adapters 的 tools.ts(MIT License):
5+
* - dereferenceJsonSchema:把 $defs/$definitions 里的 $ref 内联展开
6+
* (部分 JSON Schema 校验器与 LLM API 不解析 $ref)
7+
* - simplifyJsonSchemaForLLM:摊平 allOf/anyOf/oneOf、剥离 if/then/else/not
8+
* 等顶层组合关键字,生成 OpenAI 等工具调用 API 可接受的 schema
9+
*/
10+
11+
/**
12+
* 将 JSON Schema 中的 $ref 指针内联为 $defs/definitions 中的定义
13+
*/
14+
function dereferenceJsonSchema(schema: Record<string, any>): Record<string, any> {
15+
const definitions = schema.$defs ?? schema.definitions ?? {};
16+
17+
function resolveRefs(obj: any, visitedRefs: Set<string> = new Set()): any {
18+
if (typeof obj !== "object" || obj === null) return obj;
19+
if (obj.$ref && typeof obj.$ref === "string") {
20+
const refPath: string = obj.$ref;
21+
const match = refPath.match(/^#\/\$defs\/(.+)$/) ?? refPath.match(/^#\/definitions\/(.+)$/);
22+
if (match) {
23+
const definition = definitions[match[1]];
24+
if (definition) {
25+
// 循环引用防御:退化为空对象,避免无限递归
26+
if (visitedRefs.has(refPath)) return { type: "object" };
27+
const newVisited = new Set(visitedRefs);
28+
newVisited.add(refPath);
29+
const { $ref: _ref, ...restOfObj } = obj;
30+
return { ...resolveRefs(definition, newVisited), ...restOfObj };
31+
}
32+
}
33+
return obj;
34+
}
35+
const result: Record<string, any> = {};
36+
for (const [key, value] of Object.entries(obj)) {
37+
if (key === "$defs" || key === "definitions") continue;
38+
if (Array.isArray(value)) result[key] = value.map(item => (typeof item === "object" && item !== null ? resolveRefs(item, visitedRefs) : item));
39+
else if (typeof value === "object" && value !== null) result[key] = resolveRefs(value, visitedRefs);
40+
else result[key] = value;
41+
}
42+
return result;
43+
}
44+
45+
return resolveRefs(schema);
46+
}
47+
48+
/**
49+
* 深合并两个 JSON Schema 对象:
50+
* 数组拼接(enum 去重)、对象递归合并、基本类型覆盖
51+
*/
52+
function deepMergeSchemas(target: Record<string, any>, source: Record<string, any>): Record<string, any> {
53+
const result: Record<string, any> = { ...target };
54+
for (const [key, sourceValue] of Object.entries(source)) {
55+
const targetValue = result[key];
56+
if (key === "required" && Array.isArray(targetValue)) {
57+
result[key] = [...new Set([...targetValue, ...(Array.isArray(sourceValue) ? sourceValue : [])])];
58+
} else if (key === "const") {
59+
const values = new Set<any>();
60+
if (Array.isArray(result.enum)) result.enum.forEach(v => values.add(v));
61+
if (result.const !== undefined) values.add(result.const);
62+
values.add(sourceValue);
63+
delete result.const;
64+
result.enum = [...values];
65+
} else if (key === "enum" && Array.isArray(sourceValue)) {
66+
const values = new Set<any>();
67+
if (Array.isArray(targetValue)) targetValue.forEach(v => values.add(v));
68+
if (result.const !== undefined) {
69+
values.add(result.const);
70+
delete result.const;
71+
}
72+
sourceValue.forEach(v => values.add(v));
73+
result[key] = [...values];
74+
} else if (key === "properties" && typeof targetValue === "object" && targetValue !== null && typeof sourceValue === "object" && sourceValue !== null) {
75+
const mergedProps = { ...targetValue };
76+
for (const [propKey, propValue] of Object.entries(sourceValue)) {
77+
const existing = mergedProps[propKey];
78+
mergedProps[propKey] = (existing && typeof existing === "object" && propValue && typeof propValue === "object")
79+
? deepMergeSchemas(existing as Record<string, any>, propValue as Record<string, any>)
80+
: propValue;
81+
}
82+
result[key] = mergedProps;
83+
} else if (Array.isArray(sourceValue) && Array.isArray(targetValue)) {
84+
result[key] = [...targetValue, ...sourceValue];
85+
} else if (typeof sourceValue === "object" && sourceValue !== null && !Array.isArray(sourceValue)
86+
&& typeof targetValue === "object" && targetValue !== null && !Array.isArray(targetValue)) {
87+
result[key] = deepMergeSchemas(targetValue, sourceValue);
88+
} else {
89+
result[key] = sourceValue;
90+
}
91+
}
92+
return result;
93+
}
94+
95+
/**
96+
* 从 if/then/else 条件 schema 中提取并合并 properties / required
97+
*/
98+
function extractPropertiesFromConditional(schema: Record<string, any>): Record<string, any> {
99+
let result: Record<string, any> = {};
100+
for (const branch of [schema.then, schema.else]) {
101+
const b = branch as Record<string, any> | undefined;
102+
if (b && typeof b === "object") {
103+
if (b.properties) result = deepMergeSchemas(result, { properties: b.properties });
104+
if (b.required) result.required = [...new Set([...(result.required || []), ...b.required])];
105+
}
106+
}
107+
return result;
108+
}
109+
110+
/**
111+
* 为 LLM 工具调用 API 简化 JSON Schema:
112+
* - allOf 合并进主 schema;anyOf/oneOf 摊平为对象属性合并
113+
* - if/then/else / not / $schema / unevaluatedProperties 剥离(提取其中的属性)
114+
* 递归应用到嵌套 schema
115+
*/
116+
export function simplifyJsonSchemaForLLM(schema: Record<string, any>): Record<string, any> {
117+
if (typeof schema !== "object" || schema === null) return schema;
118+
const {
119+
allOf, anyOf, oneOf, not: _not, if: schemaIf, then: schemaThen, else: schemaElse,
120+
$schema: _$schema, unevaluatedProperties: _unevaluatedProperties, ...baseSchema
121+
} = schema;
122+
let result: Record<string, any> = { ...baseSchema };
123+
124+
if (schemaIf || schemaThen || schemaElse) {
125+
const conditionalProps = extractPropertiesFromConditional({ if: schemaIf, then: schemaThen, else: schemaElse });
126+
result = deepMergeSchemas(result, conditionalProps);
127+
}
128+
129+
if (Array.isArray(allOf)) {
130+
for (const subSchema of allOf) {
131+
if (subSchema?.if || subSchema?.then || subSchema?.else) {
132+
result = deepMergeSchemas(result, extractPropertiesFromConditional(subSchema));
133+
}
134+
result = deepMergeSchemas(result, simplifyJsonSchemaForLLM(subSchema));
135+
}
136+
}
137+
138+
const unionSchemas = anyOf || oneOf;
139+
if (Array.isArray(unionSchemas) && unionSchemas.length > 0) {
140+
const schemasToMerge = unionSchemas.filter((s: any) => typeof s === "object" && s !== null && (s.type === "object" || s.properties));
141+
const mergedProperties: Record<string, any> = {};
142+
const requiredSets: Set<string>[] = [];
143+
for (const subSchema of schemasToMerge) {
144+
const simplified = simplifyJsonSchemaForLLM(subSchema);
145+
if (simplified.properties) Object.assign(mergedProperties, simplified.properties);
146+
if (Array.isArray(simplified.required)) requiredSets.push(new Set(simplified.required));
147+
if (simplified.type && !result.type) result.type = simplified.type;
148+
}
149+
if (Object.keys(mergedProperties).length > 0) {
150+
result.properties = { ...result.properties, ...mergedProperties };
151+
}
152+
if (requiredSets.length > 0) {
153+
// 各分支 required 的交集:所有分支都要求的字段才是必填
154+
const commonRequired = requiredSets.reduce((acc, set) => new Set([...acc].filter(x => set.has(x))));
155+
if (commonRequired.size > 0) result.required = [...new Set([...(result.required || []), ...commonRequired])];
156+
}
157+
}
158+
159+
if (result.properties && !result.type) result.type = "object";
160+
if (result.properties) {
161+
const simplifiedProperties: Record<string, any> = {};
162+
for (const [propName, propSchema] of Object.entries(result.properties)) {
163+
simplifiedProperties[propName] = (typeof propSchema === "object" && propSchema !== null)
164+
? simplifyJsonSchemaForLLM(propSchema)
165+
: propSchema;
166+
}
167+
result.properties = simplifiedProperties;
168+
}
169+
if (result.items) {
170+
if (Array.isArray(result.items)) result.items = result.items.map(item => (typeof item === "object" && item !== null ? simplifyJsonSchemaForLLM(item) : item));
171+
else if (typeof result.items === "object" && result.items !== null) result.items = simplifyJsonSchemaForLLM(result.items);
172+
}
173+
if (typeof result.additionalProperties === "object" && result.additionalProperties !== null) {
174+
result.additionalProperties = simplifyJsonSchemaForLLM(result.additionalProperties);
175+
}
176+
return result;
177+
}
178+
179+
/**
180+
* 工具 inputSchema 的完整预处理入口:解引用 + LLM 兼容简化
181+
*/
182+
export function prepareToolSchema(inputSchema: Record<string, any>): Record<string, any> {
183+
const schema = { ...inputSchema };
184+
if (!schema.properties) schema.properties = {};
185+
return simplifyJsonSchemaForLLM(dereferenceJsonSchema(schema));
186+
}

0 commit comments

Comments
 (0)