@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,207 @@
|
|
|
1
|
+
import {type AuthInfo, fromJsonSchema, type McpServer, ResourceTemplate, type ServerContext} from "@modelcontextprotocol/server";
|
|
2
|
+
import {inject, logger} from "@tsed/di";
|
|
3
|
+
import type {McpUpstreamFilter, PlatformMcpUpstreamSettings} from "../interfaces/PlatformMcpUpstreamSettings.js";
|
|
4
|
+
import type {CreateMcpServerOpts} from "./createMcpServer.js";
|
|
5
|
+
import {
|
|
6
|
+
PlatformMcpGatewayService,
|
|
7
|
+
type PlatformMcpUpstreamCatalog,
|
|
8
|
+
type PlatformMcpUpstreamConnection
|
|
9
|
+
} from "../services/PlatformMcpGatewayService.js";
|
|
10
|
+
import {resolveUpstream} from "./resolveUpstream.js";
|
|
11
|
+
|
|
12
|
+
// upstream catalogs are stable objects: compile each schema once instead of on every request
|
|
13
|
+
const schemas = new WeakMap<object, ReturnType<typeof fromJsonSchema>>();
|
|
14
|
+
|
|
15
|
+
function toSchema(key: object, schema: unknown = key) {
|
|
16
|
+
let compiled = schemas.get(key);
|
|
17
|
+
|
|
18
|
+
if (!compiled) {
|
|
19
|
+
compiled = fromJsonSchema(schema as never);
|
|
20
|
+
schemas.set(key, compiled);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
return compiled;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
type Kind = "tool" | "prompt" | "resource" | "resource template";
|
|
27
|
+
|
|
28
|
+
function isAllowed(filter: McpUpstreamFilter | undefined, value: string) {
|
|
29
|
+
const match = (pattern: string | RegExp) => {
|
|
30
|
+
if (typeof pattern === "string") {
|
|
31
|
+
return pattern === value;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// a `g` or `y` pattern keeps its position between calls and would match intermittently
|
|
35
|
+
pattern.lastIndex = 0;
|
|
36
|
+
|
|
37
|
+
return pattern.test(value);
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
if (filter?.exclude?.some(match)) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return !filter?.include || filter.include.some(match);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function getRequestOptions(ctx: ServerContext) {
|
|
48
|
+
const progressToken = ctx.mcpReq._meta?.progressToken;
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
signal: ctx.mcpReq.signal,
|
|
52
|
+
...(progressToken !== undefined && {
|
|
53
|
+
onprogress: (progress: Record<string, unknown>) =>
|
|
54
|
+
ctx.mcpReq.notify({method: "notifications/progress", params: {...progress, progressToken}} as never)
|
|
55
|
+
})
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function getPromptArgsSchema(args: {name: string; description?: string; required?: boolean}[] | undefined) {
|
|
60
|
+
if (!args?.length) {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return toSchema(args, {
|
|
65
|
+
type: "object",
|
|
66
|
+
properties: Object.fromEntries(args.map(({name, description}) => [name, {type: "string", ...(description && {description})}])),
|
|
67
|
+
required: args.filter(({required}) => required).map(({name}) => name)
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function registerCatalog(
|
|
72
|
+
server: McpServer,
|
|
73
|
+
upstream: PlatformMcpUpstreamSettings,
|
|
74
|
+
label: string,
|
|
75
|
+
{client, run}: PlatformMcpUpstreamConnection,
|
|
76
|
+
catalog: PlatformMcpUpstreamCatalog,
|
|
77
|
+
taken: Record<Kind, Set<string>>
|
|
78
|
+
) {
|
|
79
|
+
const {prefix = ""} = upstream;
|
|
80
|
+
|
|
81
|
+
const register = (kind: Kind, key: string, fn: () => void) => {
|
|
82
|
+
if (taken[kind].has(key)) {
|
|
83
|
+
logger().warn({
|
|
84
|
+
event: "MCP_GATEWAY_COLLISION",
|
|
85
|
+
message: `MCP upstream "${label}": ${kind} "${key}" is already registered and is skipped.`
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
try {
|
|
92
|
+
fn();
|
|
93
|
+
taken[kind].add(key);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
logger().warn({
|
|
96
|
+
event: "MCP_GATEWAY_REGISTER_ERROR",
|
|
97
|
+
message: `MCP upstream "${label}": unable to register ${kind} "${key}".`,
|
|
98
|
+
error
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
catalog.tools
|
|
104
|
+
.filter(({name}) => isAllowed(upstream.tools, name))
|
|
105
|
+
.forEach(({name, inputSchema, outputSchema, ...opts}) => {
|
|
106
|
+
register("tool", prefix + name, () => {
|
|
107
|
+
server.registerTool(
|
|
108
|
+
prefix + name,
|
|
109
|
+
{
|
|
110
|
+
...opts,
|
|
111
|
+
inputSchema: toSchema(inputSchema),
|
|
112
|
+
...(outputSchema && {outputSchema: toSchema(outputSchema)})
|
|
113
|
+
} as never,
|
|
114
|
+
((args: Record<string, unknown>, ctx: ServerContext) =>
|
|
115
|
+
run(() => client.callTool({name, arguments: args}, getRequestOptions(ctx)))) as never
|
|
116
|
+
);
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
catalog.resources
|
|
121
|
+
.filter(({uri}) => isAllowed(upstream.resources, uri))
|
|
122
|
+
.forEach(({name, uri, ...opts}) => {
|
|
123
|
+
register("resource", uri, () => {
|
|
124
|
+
server.registerResource(
|
|
125
|
+
name,
|
|
126
|
+
uri,
|
|
127
|
+
opts as never,
|
|
128
|
+
((_: URL, ctx: ServerContext) => run(() => client.readResource({uri}, getRequestOptions(ctx)))) as never
|
|
129
|
+
);
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
catalog.resourceTemplates
|
|
134
|
+
.filter(({uriTemplate}) => isAllowed(upstream.resources, uriTemplate))
|
|
135
|
+
.forEach(({name, uriTemplate, ...opts}) => {
|
|
136
|
+
register("resource template", name, () => {
|
|
137
|
+
server.registerResource(
|
|
138
|
+
name,
|
|
139
|
+
new ResourceTemplate(uriTemplate, {list: undefined}),
|
|
140
|
+
opts as never,
|
|
141
|
+
((uri: URL, _: unknown, ctx: ServerContext) =>
|
|
142
|
+
run(() => client.readResource({uri: uri.toString()}, getRequestOptions(ctx)))) as never
|
|
143
|
+
);
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
catalog.prompts
|
|
148
|
+
.filter(({name}) => isAllowed(upstream.prompts, name))
|
|
149
|
+
.forEach(({name, arguments: args, ...opts}) => {
|
|
150
|
+
register("prompt", prefix + name, () => {
|
|
151
|
+
const argsSchema = getPromptArgsSchema(args);
|
|
152
|
+
|
|
153
|
+
server.registerPrompt(
|
|
154
|
+
prefix + name,
|
|
155
|
+
{...opts, ...(argsSchema && {argsSchema})} as never,
|
|
156
|
+
((...params: unknown[]) => {
|
|
157
|
+
const ctx = params.at(-1) as ServerContext;
|
|
158
|
+
|
|
159
|
+
return run(() =>
|
|
160
|
+
client.getPrompt(
|
|
161
|
+
{name, arguments: params.length > 1 ? (params[0] as Record<string, string>) : undefined},
|
|
162
|
+
getRequestOptions(ctx)
|
|
163
|
+
)
|
|
164
|
+
);
|
|
165
|
+
}) as never
|
|
166
|
+
);
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Registers the tools, resources and prompts of the endpoint's upstream MCP server on the given server.
|
|
173
|
+
*
|
|
174
|
+
* Local declarations take precedence over upstream entries. An unreachable upstream is logged and
|
|
175
|
+
* skipped so the endpoint keeps serving its local declarations.
|
|
176
|
+
*
|
|
177
|
+
* @param server Server already holding the local declarations.
|
|
178
|
+
* @param settings Resolved settings of the MCP endpoint.
|
|
179
|
+
* @param authInfo Verified identity of the caller, used to interpolate the upstream placeholders.
|
|
180
|
+
* @module platform/mcp
|
|
181
|
+
*/
|
|
182
|
+
export async function attachUpstream(server: McpServer, settings: CreateMcpServerOpts, authInfo?: AuthInfo) {
|
|
183
|
+
const {upstream} = settings;
|
|
184
|
+
|
|
185
|
+
if (!upstream) {
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const label = settings.path || (upstream.type === "stdio" ? upstream.command : upstream.url);
|
|
190
|
+
|
|
191
|
+
try {
|
|
192
|
+
const connection = await inject(PlatformMcpGatewayService).getConnection(upstream, resolveUpstream(upstream, authInfo));
|
|
193
|
+
|
|
194
|
+
registerCatalog(server, upstream, label, connection, await connection.getCatalog(), {
|
|
195
|
+
tool: new Set(settings.tools.map(({name}) => name)),
|
|
196
|
+
prompt: new Set(settings.prompts.map(({name}) => name)),
|
|
197
|
+
resource: new Set(settings.resources.map(({uri}) => uri!).filter(Boolean)),
|
|
198
|
+
"resource template": new Set(settings.resources.filter(({uri}) => !uri).map(({name}) => name))
|
|
199
|
+
});
|
|
200
|
+
} catch (error) {
|
|
201
|
+
logger().error({
|
|
202
|
+
event: "MCP_GATEWAY_UPSTREAM_ERROR",
|
|
203
|
+
message: `MCP upstream "${label}" is unavailable.`,
|
|
204
|
+
error
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import {createUpstreamTransport} from "./createUpstreamTransport.js";
|
|
2
|
+
|
|
3
|
+
const {StreamableHTTPClientTransport, SSEClientTransport, StdioClientTransport} = vi.hoisted(() => {
|
|
4
|
+
class FakeTransport {
|
|
5
|
+
readonly args: unknown[];
|
|
6
|
+
|
|
7
|
+
constructor(...args: unknown[]) {
|
|
8
|
+
this.args = args;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
return {
|
|
13
|
+
StreamableHTTPClientTransport: class extends FakeTransport {},
|
|
14
|
+
SSEClientTransport: class extends FakeTransport {},
|
|
15
|
+
StdioClientTransport: class extends FakeTransport {}
|
|
16
|
+
};
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
vi.mock("@modelcontextprotocol/client", () => ({StreamableHTTPClientTransport, SSEClientTransport}));
|
|
20
|
+
vi.mock("@modelcontextprotocol/client/stdio", () => ({
|
|
21
|
+
StdioClientTransport,
|
|
22
|
+
getDefaultEnvironment: () => ({PATH: "/usr/bin", HOME: "/home/tsed"})
|
|
23
|
+
}));
|
|
24
|
+
|
|
25
|
+
describe("createUpstreamTransport()", () => {
|
|
26
|
+
it("creates a Streamable HTTP transport with the upstream headers", async () => {
|
|
27
|
+
const transport = await createUpstreamTransport({
|
|
28
|
+
type: "http",
|
|
29
|
+
url: "https://upstream.example.com/mcp",
|
|
30
|
+
headers: {authorization: "Bearer abc"}
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
expect(transport).toBeInstanceOf(StreamableHTTPClientTransport);
|
|
34
|
+
expect((transport as any).args).toEqual([
|
|
35
|
+
new URL("https://upstream.example.com/mcp"),
|
|
36
|
+
{requestInit: {headers: {authorization: "Bearer abc"}}}
|
|
37
|
+
]);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it("merges the upstream headers over the request options", async () => {
|
|
41
|
+
const transport = await createUpstreamTransport({
|
|
42
|
+
type: "http",
|
|
43
|
+
url: "https://upstream.example.com/mcp",
|
|
44
|
+
requestInit: {redirect: "error", headers: {"x-static": "1", authorization: "Bearer static"}},
|
|
45
|
+
headers: {authorization: "Bearer abc"}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
expect((transport as any).args[1]).toEqual({
|
|
49
|
+
requestInit: {redirect: "error", headers: {"x-static": "1", authorization: "Bearer abc"}}
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it.each([
|
|
54
|
+
["a Headers instance", new Headers({"X-Static": "1", Authorization: "Bearer static"})],
|
|
55
|
+
[
|
|
56
|
+
"a list of tuples",
|
|
57
|
+
[
|
|
58
|
+
["X-Static", "1"],
|
|
59
|
+
["Authorization", "Bearer static"]
|
|
60
|
+
] as [string, string][]
|
|
61
|
+
]
|
|
62
|
+
])("accepts request headers given as %s", async (_, headers) => {
|
|
63
|
+
const transport = await createUpstreamTransport({
|
|
64
|
+
type: "http",
|
|
65
|
+
url: "https://upstream.example.com/mcp",
|
|
66
|
+
requestInit: {headers},
|
|
67
|
+
headers: {Authorization: "Bearer abc"}
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
expect((transport as any).args[1]).toEqual({requestInit: {headers: {"x-static": "1", authorization: "Bearer abc"}}});
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("creates a legacy SSE transport", async () => {
|
|
74
|
+
const transport = await createUpstreamTransport({type: "sse", url: "https://upstream.example.com/sse"});
|
|
75
|
+
|
|
76
|
+
expect(transport).toBeInstanceOf(SSEClientTransport);
|
|
77
|
+
expect((transport as any).args).toEqual([new URL("https://upstream.example.com/sse"), {requestInit: {headers: {}}}]);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it("creates a stdio transport inheriting the default environment", async () => {
|
|
81
|
+
const transport = await createUpstreamTransport({type: "stdio", command: "npx", args: ["-y", "server"], cwd: "/data"});
|
|
82
|
+
|
|
83
|
+
expect(transport).toBeInstanceOf(StdioClientTransport);
|
|
84
|
+
expect((transport as any).args).toEqual([{command: "npx", args: ["-y", "server"], cwd: "/data"}]);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it("merges the stdio environment over the default one", async () => {
|
|
88
|
+
const transport = await createUpstreamTransport({type: "stdio", command: "npx", env: {API_TOKEN: "abc", HOME: "/custom"}});
|
|
89
|
+
|
|
90
|
+
expect((transport as any).args).toEqual([
|
|
91
|
+
{command: "npx", args: undefined, cwd: undefined, env: {PATH: "/usr/bin", HOME: "/custom", API_TOKEN: "abc"}}
|
|
92
|
+
]);
|
|
93
|
+
});
|
|
94
|
+
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type {Transport} from "@modelcontextprotocol/client";
|
|
2
|
+
import type {PlatformMcpUpstreamSettings} from "../interfaces/PlatformMcpUpstreamSettings.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Creates the MCP client transport matching a resolved upstream definition.
|
|
6
|
+
*
|
|
7
|
+
* The client package is imported lazily so applications without upstream never load it.
|
|
8
|
+
*
|
|
9
|
+
* @module platform/mcp
|
|
10
|
+
*/
|
|
11
|
+
export async function createUpstreamTransport(upstream: PlatformMcpUpstreamSettings): Promise<Transport> {
|
|
12
|
+
if (upstream.type === "stdio") {
|
|
13
|
+
const {StdioClientTransport, getDefaultEnvironment} = await import("@modelcontextprotocol/client/stdio");
|
|
14
|
+
const {command, args, env, cwd} = upstream;
|
|
15
|
+
|
|
16
|
+
return new StdioClientTransport({command, args, cwd, ...(env && {env: {...getDefaultEnvironment(), ...env}})});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const {StreamableHTTPClientTransport, SSEClientTransport} = await import("@modelcontextprotocol/client");
|
|
20
|
+
// `requestInit.headers` may be a record, a list of tuples or a `Headers` instance
|
|
21
|
+
const headers = new Headers(upstream.requestInit?.headers);
|
|
22
|
+
|
|
23
|
+
Object.entries(upstream.headers || {}).forEach(([name, value]) => headers.set(name, value));
|
|
24
|
+
|
|
25
|
+
const requestInit: RequestInit = {...upstream.requestInit, headers: Object.fromEntries(headers)};
|
|
26
|
+
const url = new URL(upstream.url);
|
|
27
|
+
|
|
28
|
+
return upstream.type === "sse" ? new SSEClientTransport(url, {requestInit}) : new StreamableHTTPClientTransport(url, {requestInit});
|
|
29
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import {hasPlaceholders, interpolate} from "./interpolate.js";
|
|
2
|
+
|
|
3
|
+
describe("interpolate()", () => {
|
|
4
|
+
it("replaces the placeholders with the matching variables", () => {
|
|
5
|
+
expect(interpolate("Bearer ${TOKEN}", {TOKEN: "abc"})).toBe("Bearer abc");
|
|
6
|
+
expect(interpolate("${A}-${B}-${A}", {A: "1", B: "2"})).toBe("1-2-1");
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
it("leaves placeholders without a matching variable untouched", () => {
|
|
10
|
+
expect(interpolate("${TOKEN} ${OTHER}", {TOKEN: "abc"})).toBe("abc ${OTHER}");
|
|
11
|
+
expect(interpolate("${constructor}", {})).toBe("${constructor}");
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it("replaces an undefined variable with an empty string", () => {
|
|
15
|
+
expect(interpolate("Bearer ${TOKEN}", {TOKEN: undefined})).toBe("Bearer ");
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it("returns a string without placeholder as is", () => {
|
|
19
|
+
expect(interpolate("plain $TOKEN {TOKEN}", {TOKEN: "abc"})).toBe("plain $TOKEN {TOKEN}");
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
describe("hasPlaceholders()", () => {
|
|
24
|
+
it("detects one of the given placeholder names", () => {
|
|
25
|
+
expect(hasPlaceholders("Bearer ${TOKEN}", ["TOKEN", "CLIENT"])).toBe(true);
|
|
26
|
+
expect(hasPlaceholders("${OTHER} ${CLIENT}", ["TOKEN", "CLIENT"])).toBe(true);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it("ignores other placeholders and plain strings", () => {
|
|
30
|
+
expect(hasPlaceholders("${OTHER}", ["TOKEN"])).toBe(false);
|
|
31
|
+
expect(hasPlaceholders("Bearer token", ["TOKEN"])).toBe(false);
|
|
32
|
+
});
|
|
33
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const PLACEHOLDER = /\$\{([A-Za-z0-9_]+)\}/g;
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Replaces the `${NAME}` placeholders of a string with the matching variables.
|
|
5
|
+
*
|
|
6
|
+
* Placeholders without a matching variable are left untouched, and a variable set to `undefined` is replaced
|
|
7
|
+
* with an empty string.
|
|
8
|
+
*
|
|
9
|
+
* @param value String holding the placeholders.
|
|
10
|
+
* @param variables Values indexed by placeholder name.
|
|
11
|
+
* @module platform/mcp
|
|
12
|
+
*/
|
|
13
|
+
export function interpolate(value: string, variables: Record<string, string | undefined>): string {
|
|
14
|
+
return value.replace(PLACEHOLDER, (placeholder, name: string) =>
|
|
15
|
+
Object.hasOwn(variables, name) ? (variables[name] ?? "") : placeholder
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Tells whether a string references at least one of the given placeholder names.
|
|
21
|
+
*
|
|
22
|
+
* @param value String to inspect.
|
|
23
|
+
* @param names Placeholder names to look for.
|
|
24
|
+
* @module platform/mcp
|
|
25
|
+
*/
|
|
26
|
+
export function hasPlaceholders(value: string, names: readonly string[]): boolean {
|
|
27
|
+
return [...value.matchAll(PLACEHOLDER)].some(([, name]) => names.includes(name));
|
|
28
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import {listAll} from "./listAll.js";
|
|
2
|
+
|
|
3
|
+
describe("listAll()", () => {
|
|
4
|
+
it("returns nothing without calling the upstream when the capability is missing", async () => {
|
|
5
|
+
const list = vi.fn();
|
|
6
|
+
|
|
7
|
+
await expect(listAll(undefined, list, "tools")).resolves.toEqual([]);
|
|
8
|
+
expect(list).not.toHaveBeenCalled();
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it("returns the items of a single page", async () => {
|
|
12
|
+
const list = vi.fn().mockResolvedValue({tools: [{name: "a"}, {name: "b"}]});
|
|
13
|
+
|
|
14
|
+
await expect(listAll({}, list, "tools")).resolves.toEqual([{name: "a"}, {name: "b"}]);
|
|
15
|
+
expect(list).toHaveBeenCalledExactlyOnceWith({});
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it("follows the cursor until the last page", async () => {
|
|
19
|
+
const list = vi
|
|
20
|
+
.fn()
|
|
21
|
+
.mockResolvedValueOnce({resources: [{uri: "a"}], nextCursor: "page-2"})
|
|
22
|
+
.mockResolvedValueOnce({resources: [{uri: "b"}], nextCursor: "page-3"})
|
|
23
|
+
.mockResolvedValueOnce({resources: [{uri: "c"}]});
|
|
24
|
+
|
|
25
|
+
await expect(listAll(true, list, "resources")).resolves.toEqual([{uri: "a"}, {uri: "b"}, {uri: "c"}]);
|
|
26
|
+
expect(list.mock.calls).toEqual([[{}], [{cursor: "page-2"}], [{cursor: "page-3"}]]);
|
|
27
|
+
});
|
|
28
|
+
});
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export async function listAll<Item>(enabled: unknown, list: (params: {cursor?: string}) => Promise<any>, key: string): Promise<Item[]> {
|
|
2
|
+
const items: Item[] = [];
|
|
3
|
+
let cursor: string | undefined;
|
|
4
|
+
|
|
5
|
+
if (!enabled) {
|
|
6
|
+
return items;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
do {
|
|
10
|
+
const page = await list(cursor ? {cursor} : {});
|
|
11
|
+
|
|
12
|
+
items.push(...page[key]);
|
|
13
|
+
cursor = page.nextCursor;
|
|
14
|
+
} while (cursor);
|
|
15
|
+
|
|
16
|
+
return items;
|
|
17
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import {hasUpstreamPlaceholders, resolveUpstream} from "./resolveUpstream.js";
|
|
2
|
+
|
|
3
|
+
const authInfo = {token: "abc", clientId: "client", scopes: ["mcp:read", "mcp:write"]};
|
|
4
|
+
|
|
5
|
+
describe("resolveUpstream()", () => {
|
|
6
|
+
it("interpolates the caller identity in the headers of an HTTP upstream", () => {
|
|
7
|
+
const upstream = {
|
|
8
|
+
type: "http" as const,
|
|
9
|
+
url: "http://localhost/mcp/${OAUTH_TOKEN}",
|
|
10
|
+
headers: {
|
|
11
|
+
Authorization: "Bearer ${OAUTH_TOKEN}",
|
|
12
|
+
"X-Client": "${OAUTH_CLIENT_ID}",
|
|
13
|
+
"X-Scopes": "${OAUTH_SCOPES}",
|
|
14
|
+
"X-Static": "${OTHER}"
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
expect(resolveUpstream(upstream, authInfo)).toEqual({
|
|
19
|
+
...upstream,
|
|
20
|
+
headers: {
|
|
21
|
+
Authorization: "Bearer abc",
|
|
22
|
+
"X-Client": "client",
|
|
23
|
+
"X-Scopes": "mcp:read mcp:write",
|
|
24
|
+
"X-Static": "${OTHER}"
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it("interpolates the caller identity in the args and env of a stdio upstream", () => {
|
|
30
|
+
const upstream = {
|
|
31
|
+
type: "stdio" as const,
|
|
32
|
+
command: "npx",
|
|
33
|
+
args: ["-y", "server", "--token=${OAUTH_TOKEN}"],
|
|
34
|
+
env: {TOKEN: "${OAUTH_TOKEN}"}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
expect(resolveUpstream(upstream, authInfo)).toEqual({
|
|
38
|
+
...upstream,
|
|
39
|
+
args: ["-y", "server", "--token=abc"],
|
|
40
|
+
env: {TOKEN: "abc"}
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it("replaces placeholders with empty values when the caller is not authenticated", () => {
|
|
45
|
+
expect(resolveUpstream({type: "http", url: "http://localhost/mcp", headers: {authorization: "Bearer ${OAUTH_TOKEN}"}})).toEqual({
|
|
46
|
+
type: "http",
|
|
47
|
+
url: "http://localhost/mcp",
|
|
48
|
+
headers: {authorization: "Bearer "}
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("leaves definitions without headers, args or env untouched", () => {
|
|
53
|
+
expect(resolveUpstream({type: "http", url: "http://localhost/mcp"}, authInfo)).toEqual({
|
|
54
|
+
type: "http",
|
|
55
|
+
url: "http://localhost/mcp",
|
|
56
|
+
headers: undefined
|
|
57
|
+
});
|
|
58
|
+
expect(resolveUpstream({type: "stdio", command: "node"}, authInfo)).toEqual({
|
|
59
|
+
type: "stdio",
|
|
60
|
+
command: "node",
|
|
61
|
+
args: undefined,
|
|
62
|
+
env: undefined
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
describe("hasUpstreamPlaceholders()", () => {
|
|
68
|
+
it("detects placeholders in headers, args and env", () => {
|
|
69
|
+
expect(hasUpstreamPlaceholders({type: "http", url: "http://localhost", headers: {a: "${OAUTH_TOKEN}"}})).toBe(true);
|
|
70
|
+
expect(hasUpstreamPlaceholders({type: "stdio", command: "node", args: ["${OAUTH_CLIENT_ID}"]})).toBe(true);
|
|
71
|
+
expect(hasUpstreamPlaceholders({type: "stdio", command: "node", env: {A: "${OAUTH_SCOPES}"}})).toBe(true);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("ignores static definitions", () => {
|
|
75
|
+
expect(hasUpstreamPlaceholders({type: "http", url: "http://localhost", headers: {a: "b"}})).toBe(false);
|
|
76
|
+
expect(hasUpstreamPlaceholders({type: "stdio", command: "node"})).toBe(false);
|
|
77
|
+
});
|
|
78
|
+
});
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type {AuthInfo} from "@modelcontextprotocol/server";
|
|
2
|
+
import type {PlatformMcpUpstreamSettings} from "../interfaces/PlatformMcpUpstreamSettings.js";
|
|
3
|
+
import {hasPlaceholders, interpolate} from "./interpolate.js";
|
|
4
|
+
|
|
5
|
+
const OAUTH_PLACEHOLDERS = ["OAUTH_TOKEN", "OAUTH_CLIENT_ID", "OAUTH_SCOPES"] as const;
|
|
6
|
+
|
|
7
|
+
function mapValues(record: Record<string, string> | undefined, fn: (value: string) => string) {
|
|
8
|
+
return record && Object.fromEntries(Object.entries(record).map(([key, value]) => [key, fn(value)]));
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function getValues(upstream: PlatformMcpUpstreamSettings): string[] {
|
|
12
|
+
return upstream.type === "stdio"
|
|
13
|
+
? [...(upstream.args || []), ...Object.values(upstream.env || {})]
|
|
14
|
+
: Object.values(upstream.headers || {});
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Tells whether the upstream definition references the identity of the caller.
|
|
19
|
+
*/
|
|
20
|
+
export function hasUpstreamPlaceholders(upstream: PlatformMcpUpstreamSettings) {
|
|
21
|
+
return getValues(upstream).some((value) => hasPlaceholders(value, OAUTH_PLACEHOLDERS));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Replaces the `${OAUTH_*}` placeholders of an upstream definition with the verified identity of the caller.
|
|
26
|
+
*
|
|
27
|
+
* Headers are interpolated for `http` and `sse` upstreams, `args` and `env` for `stdio` upstreams.
|
|
28
|
+
*
|
|
29
|
+
* @module platform/mcp
|
|
30
|
+
*/
|
|
31
|
+
export function resolveUpstream<T extends PlatformMcpUpstreamSettings>(upstream: T, authInfo?: AuthInfo): T {
|
|
32
|
+
const variables: Record<(typeof OAUTH_PLACEHOLDERS)[number], string | undefined> = {
|
|
33
|
+
OAUTH_TOKEN: authInfo?.token,
|
|
34
|
+
OAUTH_CLIENT_ID: authInfo?.clientId,
|
|
35
|
+
OAUTH_SCOPES: authInfo?.scopes?.join(" ")
|
|
36
|
+
};
|
|
37
|
+
const resolve = (value: string) => interpolate(value, variables);
|
|
38
|
+
|
|
39
|
+
if (upstream.type === "stdio") {
|
|
40
|
+
return {...upstream, args: upstream.args?.map(resolve), env: mapValues(upstream.env, resolve)};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return {...upstream, headers: mapValues(upstream.headers, resolve)};
|
|
44
|
+
}
|