@tsed/platform-mcp 8.41.3 → 8.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/esm/cli/services/mcpServerConnect.js +17 -1
- package/lib/esm/cli/services/mcpStreamableServer.js +1 -1
- package/lib/esm/common/domain/PlatformTokenVerifier.js +169 -0
- package/lib/esm/common/errors/PlatformInvalidToken.js +11 -0
- package/lib/esm/common/errors/PlatformServerError.js +11 -0
- package/lib/esm/common/index.js +11 -0
- package/lib/esm/common/interfaces/PlatformMcpAuthSettings.js +1 -0
- package/lib/esm/common/interfaces/PlatformMcpUpstreamSettings.js +1 -0
- package/lib/esm/common/services/PlatformMcpGatewayService.js +167 -0
- package/lib/esm/common/utils/attachUpstream.js +140 -0
- package/lib/esm/common/utils/createUpstreamTransport.js +21 -0
- package/lib/esm/common/utils/interpolate.js +24 -0
- package/lib/esm/common/utils/listAll.js +13 -0
- package/lib/esm/common/utils/resolveUpstream.js +35 -0
- package/lib/esm/http/index.js +1 -0
- package/lib/esm/http/services/PlatformMcpAuthService.js +112 -0
- package/lib/esm/http/services/PlatformMcpModule.js +60 -7
- package/lib/tsconfig.esm.tsbuildinfo +1 -1
- package/lib/types/cli/services/mcpStreamableServer.d.ts +1 -1
- package/lib/types/common/domain/PlatformTokenVerifier.d.ts +59 -0
- package/lib/types/common/errors/PlatformInvalidToken.d.ts +9 -0
- package/lib/types/common/errors/PlatformServerError.d.ts +9 -0
- package/lib/types/common/index.d.ts +11 -0
- package/lib/types/common/interfaces/PlatformMcpAuthSettings.d.ts +81 -0
- package/lib/types/common/interfaces/PlatformMcpSettings.d.ts +10 -0
- package/lib/types/common/interfaces/PlatformMcpUpstreamSettings.d.ts +77 -0
- package/lib/types/common/services/PlatformMcpGatewayService.d.ts +66 -0
- package/lib/types/common/utils/attachUpstream.d.ts +14 -0
- package/lib/types/common/utils/createUpstreamTransport.d.ts +10 -0
- package/lib/types/common/utils/interpolate.d.ts +19 -0
- package/lib/types/common/utils/listAll.d.ts +3 -0
- package/lib/types/common/utils/resolveUpstream.d.ts +14 -0
- package/lib/types/http/index.d.ts +1 -0
- package/lib/types/http/services/PlatformMcpAuthService.d.ts +61 -0
- package/lib/types/http/services/PlatformMcpModule.d.ts +9 -2
- package/package.json +11 -8
- package/readme.md +2 -0
- package/src/cli/services/mcpServerConnect.spec.ts +40 -4
- package/src/cli/services/mcpServerConnect.ts +21 -1
- package/src/cli/services/mcpStreamableServer.ts +2 -2
- package/src/common/domain/PlatformTokenVerifier.spec.ts +313 -0
- package/src/common/domain/PlatformTokenVerifier.ts +230 -0
- package/src/common/errors/PlatformInvalidToken.ts +12 -0
- package/src/common/errors/PlatformServerError.ts +12 -0
- package/src/common/index.ts +11 -0
- package/src/common/interfaces/PlatformMcpAuthSettings.ts +82 -0
- package/src/common/interfaces/PlatformMcpSettings.ts +10 -0
- package/src/common/interfaces/PlatformMcpUpstreamSettings.ts +80 -0
- package/src/common/services/PlatformMcpGatewayService.spec.ts +282 -0
- package/src/common/services/PlatformMcpGatewayService.ts +247 -0
- package/src/common/utils/attachUpstream.spec.ts +305 -0
- package/src/common/utils/attachUpstream.ts +207 -0
- package/src/common/utils/createUpstreamTransport.spec.ts +94 -0
- package/src/common/utils/createUpstreamTransport.ts +29 -0
- package/src/common/utils/interpolate.spec.ts +33 -0
- package/src/common/utils/interpolate.ts +28 -0
- package/src/common/utils/listAll.spec.ts +28 -0
- package/src/common/utils/listAll.ts +17 -0
- package/src/common/utils/resolveUpstream.spec.ts +78 -0
- package/src/common/utils/resolveUpstream.ts +44 -0
- package/src/http/index.ts +1 -0
- package/src/http/services/PlatformMcpAuthService.spec.ts +239 -0
- package/src/http/services/PlatformMcpAuthService.ts +137 -0
- package/src/http/services/PlatformMcpModule.spec.ts +89 -0
- package/src/http/services/PlatformMcpModule.ts +79 -9
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import {createHash} from "node:crypto";
|
|
2
|
+
import type {Client, Prompt, Resource, ResourceTemplateType, Tool} from "@modelcontextprotocol/client";
|
|
3
|
+
import {constant, injectable, logger, type OnDestroy} from "@tsed/di";
|
|
4
|
+
import type {PlatformMcpUpstreamSettings} from "../interfaces/PlatformMcpUpstreamSettings.js";
|
|
5
|
+
import {createUpstreamTransport} from "../utils/createUpstreamTransport.js";
|
|
6
|
+
import {listAll} from "../utils/listAll.js";
|
|
7
|
+
|
|
8
|
+
const DEFAULT_POOL_MAX = 100;
|
|
9
|
+
const DEFAULT_IDLE_TIMEOUT = 300_000;
|
|
10
|
+
const MAX_RETRY_DELAY = 30_000;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Tools, resources and prompts advertised by an upstream MCP server.
|
|
14
|
+
*
|
|
15
|
+
* @module platform/mcp
|
|
16
|
+
*/
|
|
17
|
+
export interface PlatformMcpUpstreamCatalog {
|
|
18
|
+
tools: Tool[];
|
|
19
|
+
resources: Resource[];
|
|
20
|
+
resourceTemplates: ResourceTemplateType[];
|
|
21
|
+
prompts: Prompt[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Live connection to an upstream MCP server and its cached catalog.
|
|
26
|
+
*
|
|
27
|
+
* @module platform/mcp
|
|
28
|
+
*/
|
|
29
|
+
export interface PlatformMcpUpstreamConnection {
|
|
30
|
+
client: Client;
|
|
31
|
+
getCatalog(): Promise<PlatformMcpUpstreamCatalog>;
|
|
32
|
+
/**
|
|
33
|
+
* Runs an upstream request, keeping the connection out of the pool eviction while it is pending.
|
|
34
|
+
*/
|
|
35
|
+
run<T>(fn: () => Promise<T>): Promise<T>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface PoolEntry {
|
|
39
|
+
lastUsed: number;
|
|
40
|
+
pending: number;
|
|
41
|
+
connection?: Promise<PlatformMcpUpstreamConnection>;
|
|
42
|
+
client?: Client;
|
|
43
|
+
failures: number;
|
|
44
|
+
retryAt: number;
|
|
45
|
+
error?: unknown;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Owns the MCP clients connected to the upstream servers declared on the MCP endpoints.
|
|
50
|
+
*
|
|
51
|
+
* One connection is kept per upstream and per distinct set of interpolated values, so upstreams with
|
|
52
|
+
* caller-independent credentials share a single connection while forwarded identities get their own.
|
|
53
|
+
*
|
|
54
|
+
* @module platform/mcp
|
|
55
|
+
*/
|
|
56
|
+
export class PlatformMcpGatewayService implements OnDestroy {
|
|
57
|
+
protected pools = new Map<PlatformMcpUpstreamSettings, Map<string, PoolEntry>>();
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Returns the connection matching the resolved upstream definition, connecting lazily.
|
|
61
|
+
*
|
|
62
|
+
* @param upstream Upstream declared in the configuration, identifying the pool.
|
|
63
|
+
* @param resolved Same definition with its placeholders interpolated for the caller.
|
|
64
|
+
*/
|
|
65
|
+
getConnection(
|
|
66
|
+
upstream: PlatformMcpUpstreamSettings,
|
|
67
|
+
resolved: PlatformMcpUpstreamSettings = upstream
|
|
68
|
+
): Promise<PlatformMcpUpstreamConnection> {
|
|
69
|
+
const pool = this.getPool(upstream);
|
|
70
|
+
const key = this.getKey(resolved);
|
|
71
|
+
const now = Date.now();
|
|
72
|
+
let entry = pool.get(key);
|
|
73
|
+
|
|
74
|
+
if (!entry) {
|
|
75
|
+
entry = {lastUsed: now, pending: 0, failures: 0, retryAt: 0};
|
|
76
|
+
pool.set(key, entry);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
entry.lastUsed = now;
|
|
80
|
+
this.evict(upstream, pool, entry, now);
|
|
81
|
+
|
|
82
|
+
if (!entry.connection) {
|
|
83
|
+
if (entry.retryAt > now) {
|
|
84
|
+
return Promise.reject(entry.error);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
entry.connection = this.connect(resolved, entry).catch((error) => {
|
|
88
|
+
entry.connection = undefined;
|
|
89
|
+
entry.failures++;
|
|
90
|
+
entry.error = error;
|
|
91
|
+
entry.retryAt = Date.now() + Math.min(1000 * 2 ** (entry.failures - 1), MAX_RETRY_DELAY);
|
|
92
|
+
|
|
93
|
+
throw error;
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return entry.connection;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async $onDestroy() {
|
|
101
|
+
const entries = [...this.pools.values()].flatMap((pool) => [...pool.values()]);
|
|
102
|
+
|
|
103
|
+
this.pools.clear();
|
|
104
|
+
|
|
105
|
+
await Promise.all(entries.map((entry) => this.close(entry)));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
protected async connect(upstream: PlatformMcpUpstreamSettings, entry: PoolEntry): Promise<PlatformMcpUpstreamConnection> {
|
|
109
|
+
const {Client} = await import("@modelcontextprotocol/client");
|
|
110
|
+
const transport = await createUpstreamTransport(upstream);
|
|
111
|
+
let catalog: Promise<PlatformMcpUpstreamCatalog> | undefined;
|
|
112
|
+
const invalidate = () => {
|
|
113
|
+
catalog = undefined;
|
|
114
|
+
};
|
|
115
|
+
const listChanged = {autoRefresh: false, onChanged: invalidate};
|
|
116
|
+
|
|
117
|
+
const client = new Client(
|
|
118
|
+
{
|
|
119
|
+
name: constant<string>("name") || "tsed-mcp-gateway",
|
|
120
|
+
version: constant<string>("version") || "0.0.0"
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
listChanged: {tools: listChanged, prompts: listChanged, resources: listChanged}
|
|
124
|
+
}
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
entry.client = client;
|
|
128
|
+
|
|
129
|
+
client.onclose = () => {
|
|
130
|
+
// drop the connection so the next request reconnects
|
|
131
|
+
if (entry.client === client) {
|
|
132
|
+
entry.connection = undefined;
|
|
133
|
+
entry.client = undefined;
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
try {
|
|
138
|
+
await client.connect(transport);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
entry.client = undefined;
|
|
141
|
+
await client.close().catch(() => undefined);
|
|
142
|
+
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
entry.failures = 0;
|
|
147
|
+
|
|
148
|
+
return {
|
|
149
|
+
client,
|
|
150
|
+
getCatalog: () => {
|
|
151
|
+
catalog ||= this.loadCatalog(client).catch((error) => {
|
|
152
|
+
catalog = undefined;
|
|
153
|
+
|
|
154
|
+
throw error;
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
return catalog;
|
|
158
|
+
},
|
|
159
|
+
run: async (fn) => {
|
|
160
|
+
entry.pending++;
|
|
161
|
+
|
|
162
|
+
try {
|
|
163
|
+
return await fn();
|
|
164
|
+
} finally {
|
|
165
|
+
entry.pending--;
|
|
166
|
+
entry.lastUsed = Date.now();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
protected async loadCatalog(client: Client): Promise<PlatformMcpUpstreamCatalog> {
|
|
173
|
+
const capabilities = client.getServerCapabilities() || {};
|
|
174
|
+
|
|
175
|
+
const [tools, resources, resourceTemplates, prompts] = await Promise.all([
|
|
176
|
+
listAll<Tool>(capabilities.tools, (params) => client.listTools(params), "tools"),
|
|
177
|
+
listAll<Resource>(capabilities.resources, (params) => client.listResources(params), "resources"),
|
|
178
|
+
listAll<ResourceTemplateType>(capabilities.resources, (params) => client.listResourceTemplates(params), "resourceTemplates"),
|
|
179
|
+
listAll<Prompt>(capabilities.prompts, (params) => client.listPrompts(params), "prompts")
|
|
180
|
+
]);
|
|
181
|
+
|
|
182
|
+
return {tools, resources, resourceTemplates, prompts};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
protected getPool(upstream: PlatformMcpUpstreamSettings) {
|
|
186
|
+
let pool = this.pools.get(upstream);
|
|
187
|
+
|
|
188
|
+
if (!pool) {
|
|
189
|
+
pool = new Map();
|
|
190
|
+
this.pools.set(upstream, pool);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return pool;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
protected getKey(upstream: PlatformMcpUpstreamSettings) {
|
|
197
|
+
const values = upstream.type === "stdio" ? [upstream.args, upstream.env] : [upstream.headers];
|
|
198
|
+
|
|
199
|
+
return createHash("sha256").update(JSON.stringify(values)).digest("hex");
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Closes idle connections, then the least recently used ones while the pool is full.
|
|
204
|
+
* Connections serving a request and the requested one are kept, so the pool can temporarily exceed `max`.
|
|
205
|
+
*/
|
|
206
|
+
protected evict(upstream: PlatformMcpUpstreamSettings, pool: Map<string, PoolEntry>, current: PoolEntry, now: number) {
|
|
207
|
+
const {max = DEFAULT_POOL_MAX, idleTimeout = DEFAULT_IDLE_TIMEOUT} = upstream.pool || {};
|
|
208
|
+
|
|
209
|
+
if (pool.size <= 1) {
|
|
210
|
+
// a single connection (static credentials, stdio) is kept alive
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const entries = [...pool.entries()].sort(([, a], [, b]) => a.lastUsed - b.lastUsed);
|
|
215
|
+
let size = entries.length;
|
|
216
|
+
|
|
217
|
+
for (const [key, entry] of entries) {
|
|
218
|
+
if (now - entry.lastUsed < idleTimeout && size <= max) {
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (entry.pending || entry === current) {
|
|
223
|
+
// never close a connection that is serving a request, nor the one being requested
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
size--;
|
|
228
|
+
pool.delete(key);
|
|
229
|
+
void this.close(entry);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
protected async close(entry: PoolEntry) {
|
|
234
|
+
const {client} = entry;
|
|
235
|
+
|
|
236
|
+
entry.client = undefined;
|
|
237
|
+
entry.connection = undefined;
|
|
238
|
+
|
|
239
|
+
try {
|
|
240
|
+
await client?.close();
|
|
241
|
+
} catch (error) {
|
|
242
|
+
logger().warn({event: "MCP_GATEWAY_CLOSE_ERROR", error});
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
injectable(PlatformMcpGatewayService);
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import {DITest, inject, logger} from "@tsed/di";
|
|
2
|
+
import type {PlatformMcpUpstreamSettings} from "../interfaces/PlatformMcpUpstreamSettings.js";
|
|
3
|
+
import {PlatformMcpGatewayService, type PlatformMcpUpstreamCatalog} from "../services/PlatformMcpGatewayService.js";
|
|
4
|
+
import {attachUpstream} from "./attachUpstream.js";
|
|
5
|
+
import type {CreateMcpServerOpts} from "./createMcpServer.js";
|
|
6
|
+
|
|
7
|
+
const authInfo = {token: "abc", clientId: "client", scopes: ["mcp:read"]};
|
|
8
|
+
|
|
9
|
+
function createCatalog(catalog: Partial<PlatformMcpUpstreamCatalog> = {}): PlatformMcpUpstreamCatalog {
|
|
10
|
+
return {
|
|
11
|
+
tools: [
|
|
12
|
+
{
|
|
13
|
+
name: "echo",
|
|
14
|
+
description: "Echo",
|
|
15
|
+
inputSchema: {type: "object", properties: {message: {type: "string"}}},
|
|
16
|
+
outputSchema: {type: "object", properties: {message: {type: "string"}}}
|
|
17
|
+
},
|
|
18
|
+
{name: "delete", inputSchema: {type: "object"}}
|
|
19
|
+
],
|
|
20
|
+
resources: [{name: "readme", uri: "upstream://readme", mimeType: "text/plain"}],
|
|
21
|
+
resourceTemplates: [{name: "doc", uriTemplate: "upstream://docs/{id}"}],
|
|
22
|
+
prompts: [
|
|
23
|
+
{name: "greet", description: "Greet", arguments: [{name: "who", description: "Name", required: true}, {name: "lang"}]},
|
|
24
|
+
{name: "plain"}
|
|
25
|
+
],
|
|
26
|
+
...catalog
|
|
27
|
+
} as PlatformMcpUpstreamCatalog;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function createSettings(upstream?: PlatformMcpUpstreamSettings, opts: Partial<CreateMcpServerOpts> = {}): CreateMcpServerOpts {
|
|
31
|
+
return {path: "/mcp/gateway", tools: [], prompts: [], resources: [], upstream, ...opts};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function createContext(meta?: Record<string, unknown>) {
|
|
35
|
+
return {mcpReq: {signal: new AbortController().signal, _meta: meta, notify: vi.fn()}};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function setup(catalog = createCatalog()) {
|
|
39
|
+
const client = {
|
|
40
|
+
callTool: vi.fn().mockResolvedValue({content: []}),
|
|
41
|
+
readResource: vi.fn().mockResolvedValue({contents: []}),
|
|
42
|
+
getPrompt: vi.fn().mockResolvedValue({messages: []})
|
|
43
|
+
};
|
|
44
|
+
const connection = {client, getCatalog: vi.fn().mockResolvedValue(catalog), run: vi.fn((fn: () => unknown) => fn())};
|
|
45
|
+
const server = {registerTool: vi.fn(), registerResource: vi.fn(), registerPrompt: vi.fn()};
|
|
46
|
+
const getConnection = vi.spyOn(inject(PlatformMcpGatewayService), "getConnection").mockResolvedValue(connection as never);
|
|
47
|
+
|
|
48
|
+
const getHandler = (method: keyof typeof server, name: string) => server[method].mock.calls.find(([key]) => key === name)!.at(-1);
|
|
49
|
+
|
|
50
|
+
return {client, connection, server, getConnection, getHandler};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const http: PlatformMcpUpstreamSettings = {type: "http", url: "https://upstream.example.com/mcp"};
|
|
54
|
+
|
|
55
|
+
describe("attachUpstream()", () => {
|
|
56
|
+
beforeEach(() => {
|
|
57
|
+
DITest.create();
|
|
58
|
+
vi.spyOn(logger(), "warn").mockReturnValue(undefined as never);
|
|
59
|
+
vi.spyOn(logger(), "error").mockReturnValue(undefined as never);
|
|
60
|
+
});
|
|
61
|
+
afterEach(() => {
|
|
62
|
+
vi.restoreAllMocks();
|
|
63
|
+
|
|
64
|
+
return DITest.reset();
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("does nothing when the endpoint has no upstream", async () => {
|
|
68
|
+
const {server, getConnection} = setup();
|
|
69
|
+
|
|
70
|
+
await attachUpstream(server as never, createSettings());
|
|
71
|
+
|
|
72
|
+
expect(getConnection).not.toHaveBeenCalled();
|
|
73
|
+
expect(server.registerTool).not.toHaveBeenCalled();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("connects with the upstream interpolated for the caller", async () => {
|
|
77
|
+
const {server, getConnection} = setup();
|
|
78
|
+
const upstream: PlatformMcpUpstreamSettings = {...http, headers: {authorization: "Bearer ${OAUTH_TOKEN}"}};
|
|
79
|
+
|
|
80
|
+
await attachUpstream(server as never, createSettings(upstream), authInfo);
|
|
81
|
+
|
|
82
|
+
expect(getConnection).toHaveBeenCalledExactlyOnceWith(upstream, {...upstream, headers: {authorization: "Bearer abc"}});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
describe("tools", () => {
|
|
86
|
+
it("registers the upstream tools with their schemas and forwards calls", async () => {
|
|
87
|
+
const {server, client, connection, getHandler} = setup();
|
|
88
|
+
const ctx = createContext();
|
|
89
|
+
|
|
90
|
+
await attachUpstream(server as never, createSettings(http));
|
|
91
|
+
|
|
92
|
+
expect(server.registerTool.mock.calls.map(([name]) => name)).toEqual(["echo", "delete"]);
|
|
93
|
+
expect(server.registerTool).toHaveBeenCalledWith(
|
|
94
|
+
"echo",
|
|
95
|
+
{description: "Echo", inputSchema: expect.anything(), outputSchema: expect.anything()},
|
|
96
|
+
expect.any(Function)
|
|
97
|
+
);
|
|
98
|
+
expect(server.registerTool.mock.calls[1][1]).not.toHaveProperty("outputSchema");
|
|
99
|
+
|
|
100
|
+
await getHandler("registerTool", "echo")({message: "hi"}, ctx);
|
|
101
|
+
|
|
102
|
+
expect(connection.run).toHaveBeenCalledOnce();
|
|
103
|
+
expect(client.callTool).toHaveBeenCalledExactlyOnceWith({name: "echo", arguments: {message: "hi"}}, {signal: ctx.mcpReq.signal});
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it("applies the prefix and the filters, and calls the upstream with the original name", async () => {
|
|
107
|
+
const {server, client, getHandler} = setup();
|
|
108
|
+
const upstream: PlatformMcpUpstreamSettings = {...http, prefix: "up_", tools: {include: [/^e/, "delete"], exclude: ["delete"]}};
|
|
109
|
+
|
|
110
|
+
await attachUpstream(server as never, createSettings(upstream));
|
|
111
|
+
|
|
112
|
+
expect(server.registerTool.mock.calls.map(([name]) => name)).toEqual(["up_echo"]);
|
|
113
|
+
|
|
114
|
+
await getHandler("registerTool", "up_echo")({}, createContext());
|
|
115
|
+
|
|
116
|
+
expect(client.callTool).toHaveBeenCalledWith({name: "echo", arguments: {}}, expect.anything());
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it("matches global and sticky patterns consistently across requests", async () => {
|
|
120
|
+
const upstream: PlatformMcpUpstreamSettings = {...http, tools: {include: [/^echo/g], exclude: [/^delete/y]}};
|
|
121
|
+
|
|
122
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
123
|
+
const {server} = setup();
|
|
124
|
+
|
|
125
|
+
await attachUpstream(server as never, createSettings(upstream));
|
|
126
|
+
|
|
127
|
+
expect(server.registerTool.mock.calls.map(([name]) => name)).toEqual(["echo"]);
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it("forwards the upstream progress notifications when the caller asked for them", async () => {
|
|
132
|
+
const {server, client, getHandler} = setup();
|
|
133
|
+
const ctx = createContext({progressToken: "token-1"});
|
|
134
|
+
|
|
135
|
+
await attachUpstream(server as never, createSettings(http));
|
|
136
|
+
await getHandler("registerTool", "echo")({}, ctx);
|
|
137
|
+
|
|
138
|
+
const {onprogress} = client.callTool.mock.calls[0][1];
|
|
139
|
+
|
|
140
|
+
onprogress({progress: 1, total: 2});
|
|
141
|
+
|
|
142
|
+
expect(ctx.mcpReq.notify).toHaveBeenCalledExactlyOnceWith({
|
|
143
|
+
method: "notifications/progress",
|
|
144
|
+
params: {progress: 1, total: 2, progressToken: "token-1"}
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("compiles each upstream schema once across requests", async () => {
|
|
149
|
+
const catalog = createCatalog();
|
|
150
|
+
const first = setup(catalog);
|
|
151
|
+
|
|
152
|
+
await attachUpstream(first.server as never, createSettings(http));
|
|
153
|
+
|
|
154
|
+
const second = setup(catalog);
|
|
155
|
+
|
|
156
|
+
await attachUpstream(second.server as never, createSettings(http));
|
|
157
|
+
|
|
158
|
+
expect(second.server.registerTool.mock.calls[0][1].inputSchema).toBe(first.server.registerTool.mock.calls[0][1].inputSchema);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it("keeps the local tool and warns when an upstream tool has the same name", async () => {
|
|
162
|
+
const {server} = setup();
|
|
163
|
+
|
|
164
|
+
await attachUpstream(server as never, createSettings(http, {tools: [{name: "echo"}] as never}));
|
|
165
|
+
|
|
166
|
+
expect(server.registerTool.mock.calls.map(([name]) => name)).toEqual(["delete"]);
|
|
167
|
+
expect(logger().warn).toHaveBeenCalledWith({
|
|
168
|
+
event: "MCP_GATEWAY_COLLISION",
|
|
169
|
+
message: 'MCP upstream "/mcp/gateway": tool "echo" is already registered and is skipped.'
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it("skips an upstream tool that cannot be registered", async () => {
|
|
174
|
+
const {server} = setup();
|
|
175
|
+
const error = new Error("invalid schema");
|
|
176
|
+
|
|
177
|
+
server.registerTool.mockImplementationOnce(() => {
|
|
178
|
+
throw error;
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
await attachUpstream(server as never, createSettings(http));
|
|
182
|
+
|
|
183
|
+
expect(server.registerTool).toHaveBeenCalledTimes(2);
|
|
184
|
+
expect(logger().warn).toHaveBeenCalledWith({
|
|
185
|
+
event: "MCP_GATEWAY_REGISTER_ERROR",
|
|
186
|
+
message: 'MCP upstream "/mcp/gateway": unable to register tool "echo".',
|
|
187
|
+
error
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
describe("resources", () => {
|
|
193
|
+
it("registers the upstream resources and forwards reads", async () => {
|
|
194
|
+
const {server, client, getHandler} = setup();
|
|
195
|
+
const ctx = createContext();
|
|
196
|
+
|
|
197
|
+
await attachUpstream(server as never, createSettings(http));
|
|
198
|
+
|
|
199
|
+
expect(server.registerResource).toHaveBeenCalledWith("readme", "upstream://readme", {mimeType: "text/plain"}, expect.any(Function));
|
|
200
|
+
|
|
201
|
+
await getHandler("registerResource", "readme")(new URL("upstream://readme"), ctx);
|
|
202
|
+
|
|
203
|
+
expect(client.readResource).toHaveBeenCalledExactlyOnceWith({uri: "upstream://readme"}, {signal: ctx.mcpReq.signal});
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
it("registers the upstream resource templates and forwards the requested URI", async () => {
|
|
207
|
+
const {server, client, getHandler} = setup();
|
|
208
|
+
|
|
209
|
+
await attachUpstream(server as never, createSettings(http));
|
|
210
|
+
await getHandler("registerResource", "doc")(new URL("upstream://docs/42"), {id: "42"}, createContext());
|
|
211
|
+
|
|
212
|
+
expect(client.readResource).toHaveBeenCalledWith({uri: "upstream://docs/42"}, expect.anything());
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
it("skips an upstream resource template named like a local one", async () => {
|
|
216
|
+
const {server} = setup();
|
|
217
|
+
|
|
218
|
+
await attachUpstream(server as never, createSettings(http, {resources: [{name: "doc", template: {}}] as never}));
|
|
219
|
+
|
|
220
|
+
expect(server.registerResource.mock.calls.map(([name]) => name)).toEqual(["readme"]);
|
|
221
|
+
expect(logger().warn).toHaveBeenCalledWith(expect.objectContaining({event: "MCP_GATEWAY_COLLISION"}));
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
it("filters resources and templates on their URI, and skips URIs declared locally", async () => {
|
|
225
|
+
const {server} = setup(
|
|
226
|
+
createCatalog({
|
|
227
|
+
resources: [
|
|
228
|
+
{name: "readme", uri: "upstream://readme"},
|
|
229
|
+
{name: "secret", uri: "upstream://secret"},
|
|
230
|
+
{name: "local", uri: "tsed://local"}
|
|
231
|
+
]
|
|
232
|
+
} as never)
|
|
233
|
+
);
|
|
234
|
+
const upstream: PlatformMcpUpstreamSettings = {...http, resources: {exclude: ["upstream://secret", /docs/]}};
|
|
235
|
+
|
|
236
|
+
await attachUpstream(server as never, createSettings(upstream, {resources: [{name: "local", uri: "tsed://local"}] as never}));
|
|
237
|
+
|
|
238
|
+
expect(server.registerResource.mock.calls.map(([name]) => name)).toEqual(["readme"]);
|
|
239
|
+
});
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
describe("prompts", () => {
|
|
243
|
+
it("registers the upstream prompts with an arguments schema and forwards them", async () => {
|
|
244
|
+
const {server, client, getHandler} = setup();
|
|
245
|
+
const ctx = createContext();
|
|
246
|
+
|
|
247
|
+
await attachUpstream(server as never, createSettings({...http, prefix: "up_"}));
|
|
248
|
+
|
|
249
|
+
expect(server.registerPrompt).toHaveBeenCalledWith(
|
|
250
|
+
"up_greet",
|
|
251
|
+
{description: "Greet", argsSchema: expect.anything()},
|
|
252
|
+
expect.any(Function)
|
|
253
|
+
);
|
|
254
|
+
|
|
255
|
+
await getHandler("registerPrompt", "up_greet")({who: "Ts.ED"}, ctx);
|
|
256
|
+
|
|
257
|
+
expect(client.getPrompt).toHaveBeenCalledExactlyOnceWith({name: "greet", arguments: {who: "Ts.ED"}}, {signal: ctx.mcpReq.signal});
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it("registers a prompt without arguments", async () => {
|
|
261
|
+
const {server, client, getHandler} = setup();
|
|
262
|
+
|
|
263
|
+
await attachUpstream(server as never, createSettings(http));
|
|
264
|
+
|
|
265
|
+
expect(server.registerPrompt).toHaveBeenCalledWith("plain", {}, expect.any(Function));
|
|
266
|
+
|
|
267
|
+
await getHandler("registerPrompt", "plain")(createContext());
|
|
268
|
+
|
|
269
|
+
expect(client.getPrompt).toHaveBeenCalledWith({name: "plain", arguments: undefined}, expect.anything());
|
|
270
|
+
});
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
describe("unavailable upstream", () => {
|
|
274
|
+
it.each([
|
|
275
|
+
["the endpoint path", createSettings(http), "/mcp/gateway"],
|
|
276
|
+
["the upstream URL", createSettings(http, {path: undefined}), "https://upstream.example.com/mcp"],
|
|
277
|
+
["the stdio command", createSettings({type: "stdio", command: "npx"}, {path: undefined}), "npx"]
|
|
278
|
+
])("logs the failure with %s and keeps the server usable", async (_, settings, label) => {
|
|
279
|
+
const {server, getConnection} = setup();
|
|
280
|
+
const error = new Error("connect ECONNREFUSED");
|
|
281
|
+
|
|
282
|
+
getConnection.mockRejectedValue(error);
|
|
283
|
+
|
|
284
|
+
await expect(attachUpstream(server as never, settings)).resolves.toBeUndefined();
|
|
285
|
+
|
|
286
|
+
expect(server.registerTool).not.toHaveBeenCalled();
|
|
287
|
+
expect(logger().error).toHaveBeenCalledWith({
|
|
288
|
+
event: "MCP_GATEWAY_UPSTREAM_ERROR",
|
|
289
|
+
message: `MCP upstream "${label}" is unavailable.`,
|
|
290
|
+
error
|
|
291
|
+
});
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
it("logs a catalog failure", async () => {
|
|
295
|
+
const {server, connection} = setup();
|
|
296
|
+
|
|
297
|
+
connection.getCatalog.mockRejectedValue(new Error("list failed"));
|
|
298
|
+
|
|
299
|
+
await attachUpstream(server as never, createSettings(http));
|
|
300
|
+
|
|
301
|
+
expect(server.registerTool).not.toHaveBeenCalled();
|
|
302
|
+
expect(logger().error).toHaveBeenCalledWith(expect.objectContaining({event: "MCP_GATEWAY_UPSTREAM_ERROR"}));
|
|
303
|
+
});
|
|
304
|
+
});
|
|
305
|
+
});
|