forked from MiniMax-AI/OpenRoom
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcpBridgeTools.ts
More file actions
196 lines (171 loc) · 5.18 KB
/
mcpBridgeTools.ts
File metadata and controls
196 lines (171 loc) · 5.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import type { ToolDef } from './llmClient';
export interface McpBridgeServer {
name: string;
command: string;
args?: string[];
env?: Record<string, string>;
}
export interface McpBridgeTool {
server: string;
name: string;
description?: string;
inputSchema?: Record<string, unknown>;
}
export interface McpBridgeToolIndex {
toolDefs: ToolDef[];
index: Record<string, McpBridgeTool>;
tools: McpBridgeTool[];
errors: Array<{ server: string; error: string }>;
}
const MCP_NAME_PREFIX = 'mcp__';
function safeJsonParse<T>(raw: string, fallback: T): T {
try {
return JSON.parse(raw) as T;
} catch {
return fallback;
}
}
function asObject(input: unknown): Record<string, unknown> {
return input && typeof input === 'object' && !Array.isArray(input)
? (input as Record<string, unknown>)
: {};
}
function sanitizeName(value: string): string {
return (value || '')
.trim()
.toLowerCase()
.replace(/[^a-z0-9_]+/g, '_')
.replace(/^_+|_+$/g, '')
.slice(0, 80);
}
export function toMcpToolName(server: string, tool: string): string {
const s = sanitizeName(server) || 'server';
const t = sanitizeName(tool) || 'tool';
return `${MCP_NAME_PREFIX}${s}__${t}`;
}
export function isMcpToolName(toolName: string): boolean {
return toolName.startsWith(MCP_NAME_PREFIX);
}
function toToolDef(item: McpBridgeTool): ToolDef {
const schema = asObject(item.inputSchema);
const toolName = toMcpToolName(item.server, item.name);
const hasObjectSchema = schema.type === 'object';
const normalizedParameters: ToolDef['function']['parameters'] = hasObjectSchema
? {
type: 'object',
properties:
schema.properties &&
typeof schema.properties === 'object' &&
!Array.isArray(schema.properties)
? (schema.properties as Record<string, unknown>)
: {},
required: Array.isArray(schema.required) ? schema.required.map((v) => String(v)) : [],
}
: {
type: 'object',
properties: {
payload_json: {
type: 'string',
description: 'JSON string payload for the MCP tool call',
},
},
required: [],
};
return {
type: 'function',
function: {
name: toolName,
description: `[MCP:${item.server}] ${item.description || item.name}`,
parameters: normalizedParameters,
},
};
}
export async function loadMcpBridgeToolIndex(): Promise<McpBridgeToolIndex> {
try {
const res = await fetch('/api/mcp-tools');
const data = safeJsonParse<{
ok?: boolean;
tools?: McpBridgeTool[];
errors?: Array<{ server: string; error: string }>;
}>(await res.text(), {});
const tools = Array.isArray(data.tools) ? data.tools : [];
const index: Record<string, McpBridgeTool> = {};
const toolDefs: ToolDef[] = [];
for (const item of tools) {
if (!item?.server || !item?.name) continue;
const toolName = toMcpToolName(item.server, item.name);
index[toolName] = item;
toolDefs.push(toToolDef(item));
}
return {
tools,
index,
toolDefs,
errors: Array.isArray(data.errors) ? data.errors : [],
};
} catch {
return { tools: [], index: {}, toolDefs: [], errors: [] };
}
}
function normalizeMcpParams(input: Record<string, unknown>): Record<string, unknown> {
if (typeof input.payload_json === 'string' && input.payload_json.trim()) {
const parsed = safeJsonParse<Record<string, unknown>>(input.payload_json, {});
return asObject(parsed);
}
const output: Record<string, unknown> = {};
for (const [k, v] of Object.entries(input)) {
if (k === 'payload_json') continue;
output[k] = v;
}
return output;
}
export async function executeMcpBridgeTool(
toolName: string,
params: Record<string, unknown>,
index: Record<string, McpBridgeTool>,
): Promise<string> {
const target = index[toolName];
if (!target) {
return `error: MCP tool not found for ${toolName}`;
}
const payload = {
server: target.server,
tool: target.name,
arguments: normalizeMcpParams(params),
};
const res = await fetch('/api/mcp-call', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
const text = await res.text();
const data = safeJsonParse<{ ok?: boolean; result?: unknown; error?: string }>(text, {});
if (!res.ok || !data.ok) {
return `error: ${data.error || text || `HTTP ${res.status}`}`;
}
if (typeof data.result === 'string') {
return data.result;
}
return JSON.stringify(data.result, null, 2);
}
export async function loadMcpBridgeServers(): Promise<McpBridgeServer[]> {
try {
const res = await fetch('/api/mcp-servers');
const data = safeJsonParse<{ servers?: McpBridgeServer[] }>(await res.text(), {});
return Array.isArray(data.servers) ? data.servers : [];
} catch {
return [];
}
}
export async function saveMcpBridgeServers(servers: McpBridgeServer[]): Promise<boolean> {
try {
const res = await fetch('/api/mcp-servers', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ servers }),
});
return res.ok;
} catch {
return false;
}
}