-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbridge.ts
More file actions
183 lines (164 loc) · 5.9 KB
/
Copy pathbridge.ts
File metadata and controls
183 lines (164 loc) · 5.9 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
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import {
CallParamsSchema,
SearchParamsSchema,
SchemaParamsSchema,
type McpToolResult,
} from "./types.js";
export class BridgeServer {
private readonly server: McpServer;
private client: Client | null = null;
private clientPromise: Promise<Client> | null = null;
private readonly primaryUrl: string;
constructor(port: number) {
this.primaryUrl = `http://127.0.0.1:${port}/mcp`;
this.server = new McpServer({
name: "mcp-proxy-bridge",
version: "1.0.0",
});
this.setupTools();
}
private setupTools(): void {
this.server.registerTool(
"mcp_search",
{
title: "Search MCP Tools",
description:
"Discover available tools across all connected MCP servers. Returns a short list of relevant tools with refs and usage hints. Use this before mcp_call to find the right tool.",
inputSchema: {
query: SearchParamsSchema.shape.query,
limit: SearchParamsSchema.shape.limit,
},
},
async (params) => this.forward("mcp_search", params),
);
this.server.registerTool(
"mcp_call",
{
title: "Call MCP Tool",
description: [
"Execute a tool on an upstream MCP server. Use the ref from mcp_search results. Returns normalized, token-efficient output with pagination support.",
"",
"IMPORTANT — Output shaping behavior:",
"• By default (detail=false), the proxy STRIPS metadata fields (id, url, created_at, updated_at, etc.), TRUNCATES text fields to 500 chars, and LIMITS arrays to 5 items. This saves tokens but may hide important data.",
"• When detail=true, ALL fields are preserved (nothing is stripped), text fields are truncated at 1500 chars, and arrays are returned in full. Use this when you need complete data — e.g. thread messages, full API responses, or when default output seems incomplete.",
"",
"Rule of thumb: if the default call returns fewer items or less data than expected, retry with detail=true.",
].join("\n"),
inputSchema: {
ref: CallParamsSchema.shape.ref,
args: CallParamsSchema.shape.args,
page_cursor: CallParamsSchema.shape.page_cursor,
detail: CallParamsSchema.shape.detail,
},
},
async (params) => this.forward("mcp_call", params),
);
this.server.registerTool(
"mcp_schema",
{
title: "Get Tool Schema",
description:
"Get the full input schema for a tool. Use the ref from mcp_search results to see all parameters, types, and required fields before calling mcp_call.",
inputSchema: {
ref: SchemaParamsSchema.shape.ref,
},
},
async (params) => this.forward("mcp_schema", params),
);
}
private async ensureClient(): Promise<Client> {
if (this.client) return this.client;
if (this.clientPromise) return this.clientPromise;
this.clientPromise = (async () => {
const url = new URL(this.primaryUrl);
let client = new Client({
name: "mcp-proxy-bridge-client",
version: "1.0.0",
});
try {
const transport = new StreamableHTTPClientTransport(url);
await client.connect(transport);
} catch {
console.error("[bridge] StreamableHTTP failed, trying SSE...");
client = new Client({
name: "mcp-proxy-bridge-client",
version: "1.0.0",
});
const sseTransport = new SSEClientTransport(url);
await client.connect(sseTransport);
}
console.error(`[bridge] Connected to primary at ${this.primaryUrl}`);
this.client = client;
return client;
})().catch((err) => {
this.clientPromise = null;
throw err;
});
return this.clientPromise;
}
private async forward(
toolName: string,
args: Record<string, unknown>,
): Promise<McpToolResult> {
try {
const client = await this.ensureClient();
const result = await client.callTool({
name: toolName,
arguments: args,
});
if (result.content && Array.isArray(result.content)) {
return { content: result.content as McpToolResult["content"] };
}
return {
content: [{ type: "text", text: JSON.stringify(result) }],
};
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
console.error(`[bridge] Forward failed: ${msg}`);
this.client = null;
return {
content: [
{
type: "text",
text: JSON.stringify({
error: `Bridge forward failed: ${msg}`,
}),
},
],
};
}
}
async start(): Promise<void> {
const transport = new StdioServerTransport();
await this.server.connect(transport);
console.error(`[bridge] Stdio transport connected, forwarding to primary at ${this.primaryUrl}`);
}
async cleanup(): Promise<void> {
try {
if (this.client) {
await this.client.close();
this.client = null;
this.clientPromise = null;
}
} catch (error) {
console.error(
"[bridge] Error during cleanup:",
error instanceof Error ? error.message : error,
);
}
}
setupGracefulShutdown(): void {
const shutdown = async (signal: string): Promise<void> => {
console.error(`[bridge] Received ${signal}, shutting down...`);
await this.cleanup();
process.exit(0);
};
process.on("SIGINT", () => shutdown("SIGINT"));
process.on("SIGTERM", () => shutdown("SIGTERM"));
}
}