@ttoss/http-server-mcp 0.12.3 → 0.12.5

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/dist/index.mjs ADDED
@@ -0,0 +1,302 @@
1
+ /** Powered by @ttoss/config. https://ttoss.dev/docs/modules/packages/config/ */
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
4
+ import { Router } from "@ttoss/http-server";
5
+ import { z, z as z$1 } from "zod";
6
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
+
8
+ //#region src/index.ts
9
+ const requestContextStore = new AsyncLocalStorage();
10
+ /**
11
+ * Generic HTTP helper for use inside MCP tool handlers.
12
+ *
13
+ * Accepts any full URL (third-party APIs, public APIs, etc.) or a path
14
+ * relative to the `apiBaseUrl` configured in `createMcpRouter`.
15
+ *
16
+ * Headers configured via `getApiHeaders` in `createMcpRouter` are injected
17
+ * automatically into every request, allowing transparent forwarding of auth
18
+ * tokens, API keys, or any other header — without coupling this helper to a
19
+ * specific authentication scheme. Per-call `options.headers` take precedence
20
+ * over context-injected headers.
21
+ *
22
+ * @param method - HTTP method (e.g. `'GET'`, `'POST'`, `'PUT'`, `'DELETE'`)
23
+ * @param url - Full URL **or** a path starting with `/` (appended to `apiBaseUrl`)
24
+ * @param options - Optional body and per-call header overrides
25
+ * @returns Parsed JSON response body
26
+ *
27
+ * @example Bearer token forwarding (configured once in `createMcpRouter`)
28
+ * ```typescript
29
+ * import { apiCall, createMcpRouter, McpServer } from '@ttoss/http-server-mcp';
30
+ *
31
+ * // Tool handler – no manual auth wiring needed
32
+ * mcpServer.registerTool('list-portfolios', { description: '...', inputSchema: {} }, async () => {
33
+ * const data = await apiCall('GET', '/portfolios');
34
+ * return { content: [{ type: 'text', text: JSON.stringify(data) }] };
35
+ * });
36
+ *
37
+ * const mcpRouter = createMcpRouter(mcpServer, {
38
+ * apiBaseUrl: `http://localhost:${process.env.PORT}/api/v1`,
39
+ * // Forward the caller's Bearer token to every apiCall
40
+ * getApiHeaders: (ctx) => ({ Authorization: ctx.headers.authorization ?? '' }),
41
+ * });
42
+ * ```
43
+ *
44
+ * @example x-api-key forwarding
45
+ * ```typescript
46
+ * const mcpRouter = createMcpRouter(mcpServer, {
47
+ * apiBaseUrl: 'https://internal-service/api',
48
+ * getApiHeaders: (ctx) => ({
49
+ * 'x-api-key': ctx.headers['x-api-key'] as string,
50
+ * }),
51
+ * });
52
+ * ```
53
+ *
54
+ * @example Third-party or public API (full URL, no context required)
55
+ * ```typescript
56
+ * const weather = await apiCall('GET', 'https://api.weather.com/current?city=Berlin');
57
+ * const created = await apiCall('POST', 'https://api.example.com/items', {
58
+ * body: { name: 'widget' },
59
+ * headers: { Authorization: 'Bearer fixed-service-token' },
60
+ * });
61
+ * ```
62
+ */
63
+ const apiCall = async (method, url, options) => {
64
+ const context = requestContextStore.getStore();
65
+ let resolvedUrl = url;
66
+ if (url.startsWith("/")) {
67
+ if (!context?.apiBaseUrl) throw new Error(`apiCall received a relative path ("${url}") but no apiBaseUrl is configured. Either pass a full URL or set apiBaseUrl in createMcpRouter options.`);
68
+ resolvedUrl = `${context.apiBaseUrl.replace(/\/$/, "")}${url}`;
69
+ }
70
+ const hasBody = options?.body !== void 0;
71
+ const headers = {
72
+ ...(context !== void 0 ? context.apiHeaders : {}),
73
+ ...(options?.headers ?? {})
74
+ };
75
+ const hasExplicitContentType = Object.keys(headers).some(headerName => {
76
+ return headerName.toLowerCase() === "content-type";
77
+ });
78
+ if (hasBody && !hasExplicitContentType) headers["Content-Type"] = "application/json";
79
+ const response = await fetch(resolvedUrl, {
80
+ method,
81
+ headers,
82
+ body: hasBody ? JSON.stringify(options.body) : void 0
83
+ });
84
+ if (!response.ok) {
85
+ const err = await response.json().catch(() => {
86
+ return {
87
+ error: response.statusText
88
+ };
89
+ });
90
+ throw new Error(err.error || `HTTP ${response.status}`);
91
+ }
92
+ if (response.status === 204 || response.status === 205) return;
93
+ if (response.headers.get("content-type")?.includes("application/json")) return response.json();
94
+ return response.text();
95
+ };
96
+ /**
97
+ * Creates a Koa router configured to handle MCP protocol requests
98
+ *
99
+ * @param server - The MCP server instance with registered tools and resources
100
+ * @param options - Configuration options for the router
101
+ * @returns A Koa Router instance configured for MCP
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * import { App, bodyParser } from '@ttoss/http-server';
106
+ * import { createMcpRouter, McpServer, z } from '@ttoss/http-server-mcp';
107
+ *
108
+ * const mcpServer = new McpServer({
109
+ * name: 'my-server',
110
+ * version: '1.0.0',
111
+ * });
112
+ *
113
+ * mcpServer.registerTool(
114
+ * 'hello',
115
+ * {
116
+ * description: 'Say hello',
117
+ * inputSchema: { name: z.string() },
118
+ * },
119
+ * async ({ name }) => ({
120
+ * content: [{ type: 'text', text: `Hello, ${name}!` }],
121
+ * })
122
+ * );
123
+ *
124
+ * const app = new App();
125
+ * app.use(bodyParser());
126
+ *
127
+ * const mcpRouter = createMcpRouter(mcpServer);
128
+ * app.use(mcpRouter.routes());
129
+ *
130
+ * app.listen(3000);
131
+ * ```
132
+ */
133
+ const createMcpRouter = (server, options = {}) => {
134
+ const {
135
+ path = "/mcp",
136
+ sessionIdGenerator,
137
+ apiBaseUrl,
138
+ getApiHeaders
139
+ } = options;
140
+ const isStateful = sessionIdGenerator !== void 0;
141
+ const needsContext = apiBaseUrl !== void 0 || getApiHeaders !== void 0;
142
+ let sharedTransport;
143
+ if (isStateful) {
144
+ sharedTransport = new StreamableHTTPServerTransport({
145
+ sessionIdGenerator,
146
+ enableJsonResponse: true
147
+ });
148
+ server.connect(sharedTransport);
149
+ }
150
+ let statelessQueue = Promise.resolve();
151
+ const enqueueStateless = work => {
152
+ const result = statelessQueue.then(() => {
153
+ return work();
154
+ });
155
+ statelessQueue = result.catch(() => {});
156
+ return result;
157
+ };
158
+ const router = new Router();
159
+ const handleWithContext = async (ctx, body) => {
160
+ const apiHeaders = getApiHeaders ? getApiHeaders(ctx) : {};
161
+ const runRequest = async transport => {
162
+ await transport.handleRequest(ctx.req, ctx.res, body);
163
+ ctx.respond = false;
164
+ };
165
+ if (isStateful && sharedTransport) {
166
+ if (needsContext) await requestContextStore.run({
167
+ apiBaseUrl,
168
+ apiHeaders
169
+ }, () => {
170
+ return runRequest(sharedTransport);
171
+ });else await runRequest(sharedTransport);
172
+ } else await enqueueStateless(async () => {
173
+ const transport = new StreamableHTTPServerTransport({
174
+ sessionIdGenerator: void 0,
175
+ enableJsonResponse: true
176
+ });
177
+ try {
178
+ await server.connect(transport);
179
+ if (needsContext) await requestContextStore.run({
180
+ apiBaseUrl,
181
+ apiHeaders
182
+ }, () => {
183
+ return runRequest(transport);
184
+ });else await runRequest(transport);
185
+ } finally {
186
+ await transport.close();
187
+ }
188
+ });
189
+ };
190
+ router.post(path, async ctx => {
191
+ try {
192
+ await handleWithContext(ctx, ctx.request.body);
193
+ } catch (error) {
194
+ if (!ctx.res.headersSent) {
195
+ ctx.status = 500;
196
+ ctx.body = {
197
+ error: error instanceof Error ? error.message : "Internal server error"
198
+ };
199
+ }
200
+ }
201
+ });
202
+ router.delete(path, async ctx => {
203
+ try {
204
+ await handleWithContext(ctx);
205
+ } catch (error) {
206
+ if (!ctx.res.headersSent) {
207
+ ctx.status = 500;
208
+ ctx.body = {
209
+ error: error instanceof Error ? error.message : "Internal server error"
210
+ };
211
+ }
212
+ }
213
+ });
214
+ return router;
215
+ };
216
+ const rawSchemaRegistryMap = /* @__PURE__ */new WeakMap();
217
+ const patchedServerSet = /* @__PURE__ */new WeakSet();
218
+ /**
219
+ * Registers a tool on an MCP server using a **plain JSON Schema** object for
220
+ * `inputSchema` instead of a Zod shape.
221
+ *
222
+ * This is useful when tool definitions are shared between the MCP server and an
223
+ * AI SDK agent (e.g. Vercel AI SDK's `tool()` helper), because both consume a
224
+ * plain JSON Schema at runtime. Using this helper eliminates the lossy
225
+ * JSON-Schema→Zod conversion that would otherwise be required.
226
+ *
227
+ * Internally the helper:
228
+ * 1. Registers the tool via the standard `McpServer.registerTool` API using a
229
+ * Zod `z.record(z.unknown())` pass-through schema so that the existing MCP
230
+ * `tools/call` handler correctly routes requests and delivers raw args to
231
+ * your handler.
232
+ * 2. Stores the original JSON Schema and patches the `tools/list` response
233
+ * handler so clients receive the verbatim JSON Schema over the wire.
234
+ *
235
+ * @param server - The `McpServer` instance to register the tool on.
236
+ * @param params - Tool configuration including name, description, inputSchema,
237
+ * and handler.
238
+ *
239
+ * @example
240
+ * ```typescript
241
+ * import { registerToolFromSchema, McpServer } from '@ttoss/http-server-mcp';
242
+ *
243
+ * const server = new McpServer({ name: 'my-server', version: '1.0.0' });
244
+ *
245
+ * registerToolFromSchema(server, {
246
+ * name: 'get-project',
247
+ * description: 'Get a project by ID',
248
+ * inputSchema: {
249
+ * type: 'object',
250
+ * properties: { id: { type: 'string', description: 'Project public ID' } },
251
+ * required: ['id'],
252
+ * },
253
+ * handler: async ({ id }) => ({
254
+ * content: [{ type: 'text', text: `Project: ${id}` }],
255
+ * }),
256
+ * });
257
+ * ```
258
+ */
259
+ const registerToolFromSchema = (server, params) => {
260
+ const {
261
+ name,
262
+ description,
263
+ inputSchema = {
264
+ type: "object",
265
+ properties: {}
266
+ },
267
+ handler
268
+ } = params;
269
+ if (!rawSchemaRegistryMap.has(server)) rawSchemaRegistryMap.set(server, /* @__PURE__ */new Map());
270
+ rawSchemaRegistryMap.get(server).set(name, inputSchema);
271
+ server.registerTool(name, {
272
+ description,
273
+ inputSchema: z$1.record(z$1.string(), z$1.unknown())
274
+ }, async args => {
275
+ return handler(args);
276
+ });
277
+ if (!patchedServerSet.has(server)) {
278
+ patchedServerSet.add(server);
279
+ const rawServer = server.server;
280
+ const origHandler = rawServer?._requestHandlers?.get("tools/list");
281
+ if (!origHandler && process.env.NODE_ENV !== "production") console.warn("[registerToolFromSchema] Could not patch tools/list — internal MCP SDK structure may have changed. The tool will still be callable, but tools/list may return a Zod-derived schema instead of the verbatim JSON Schema.");
282
+ if (origHandler) rawServer._requestHandlers.set("tools/list", async (rawRequest, extra) => {
283
+ const result = await origHandler(rawRequest, extra);
284
+ const schemas = rawSchemaRegistryMap.get(server);
285
+ if (!schemas) return result;
286
+ return {
287
+ ...result,
288
+ tools: result.tools.map(tool => {
289
+ const raw = schemas.get(tool.name);
290
+ if (raw !== void 0) return {
291
+ ...tool,
292
+ inputSchema: raw
293
+ };
294
+ return tool;
295
+ })
296
+ };
297
+ });
298
+ }
299
+ };
300
+
301
+ //#endregion
302
+ export { McpServer, apiCall, createMcpRouter, registerToolFromSchema, z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ttoss/http-server-mcp",
3
- "version": "0.12.3",
3
+ "version": "0.12.5",
4
4
  "description": "Model Context Protocol (MCP) server integration for @ttoss/http-server",
5
5
  "keywords": [
6
6
  "ai",
@@ -35,14 +35,14 @@
35
35
  "dependencies": {
36
36
  "@modelcontextprotocol/sdk": "^1.29.0",
37
37
  "zod": "^4.3.6",
38
- "@ttoss/http-server": "^0.5.12"
38
+ "@ttoss/http-server": "^0.5.14"
39
39
  },
40
40
  "devDependencies": {
41
41
  "@types/koa": "^3.0.2",
42
42
  "jest": "^30.3.0",
43
43
  "supertest": "^7.2.2",
44
- "tsup": "^8.5.1",
45
- "@ttoss/config": "^1.37.11"
44
+ "tsdown": "^0.22.0",
45
+ "@ttoss/config": "^1.37.13"
46
46
  },
47
47
  "peerDependencies": {
48
48
  "@modelcontextprotocol/sdk": "^1.0.0"
@@ -52,7 +52,7 @@
52
52
  "provenance": true
53
53
  },
54
54
  "scripts": {
55
- "build": "tsup",
55
+ "build": "tsdown",
56
56
  "test": "jest --projects tests/unit"
57
57
  }
58
58
  }
package/dist/esm/index.js DELETED
@@ -1,205 +0,0 @@
1
- /** Powered by @ttoss/config. https://ttoss.dev/docs/modules/packages/config/ */
2
- var __defProp = Object.defineProperty;
3
- var __name = (target, value) => __defProp(target, "name", {
4
- value,
5
- configurable: true
6
- });
7
-
8
- // src/index.ts
9
- import { AsyncLocalStorage } from "async_hooks";
10
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
11
- import { Router } from "@ttoss/http-server";
12
- import { z } from "zod";
13
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
14
- import { z as z2 } from "zod";
15
- var requestContextStore = new AsyncLocalStorage();
16
- var apiCall = /* @__PURE__ */__name(async (method, url, options) => {
17
- const context = requestContextStore.getStore();
18
- let resolvedUrl = url;
19
- if (url.startsWith("/")) {
20
- if (!context?.apiBaseUrl) {
21
- throw new Error(`apiCall received a relative path ("${url}") but no apiBaseUrl is configured. Either pass a full URL or set apiBaseUrl in createMcpRouter options.`);
22
- }
23
- resolvedUrl = `${context.apiBaseUrl.replace(/\/$/, "")}${url}`;
24
- }
25
- const hasBody = options?.body !== void 0;
26
- const headers = {
27
- ...(context !== void 0 ? context.apiHeaders : {}),
28
- ...(options?.headers ?? {})
29
- };
30
- const hasExplicitContentType = Object.keys(headers).some(headerName => {
31
- return headerName.toLowerCase() === "content-type";
32
- });
33
- if (hasBody && !hasExplicitContentType) {
34
- headers["Content-Type"] = "application/json";
35
- }
36
- const response = await fetch(resolvedUrl, {
37
- method,
38
- headers,
39
- body: hasBody ? JSON.stringify(options.body) : void 0
40
- });
41
- if (!response.ok) {
42
- const err = await response.json().catch(() => {
43
- return {
44
- error: response.statusText
45
- };
46
- });
47
- throw new Error(err.error || `HTTP ${response.status}`);
48
- }
49
- if (response.status === 204 || response.status === 205) {
50
- return void 0;
51
- }
52
- const contentType = response.headers.get("content-type");
53
- if (contentType?.includes("application/json")) {
54
- return response.json();
55
- }
56
- return response.text();
57
- }, "apiCall");
58
- var createMcpRouter = /* @__PURE__ */__name((server, options = {}) => {
59
- const {
60
- path = "/mcp",
61
- sessionIdGenerator,
62
- apiBaseUrl,
63
- getApiHeaders
64
- } = options;
65
- const isStateful = sessionIdGenerator !== void 0;
66
- const needsContext = apiBaseUrl !== void 0 || getApiHeaders !== void 0;
67
- let sharedTransport;
68
- if (isStateful) {
69
- sharedTransport = new StreamableHTTPServerTransport({
70
- sessionIdGenerator,
71
- enableJsonResponse: true
72
- });
73
- server.connect(sharedTransport);
74
- }
75
- let statelessQueue = Promise.resolve();
76
- const enqueueStateless = /* @__PURE__ */__name(work => {
77
- const result = statelessQueue.then(() => {
78
- return work();
79
- });
80
- statelessQueue = result.catch(() => {});
81
- return result;
82
- }, "enqueueStateless");
83
- const router = new Router();
84
- const handleWithContext = /* @__PURE__ */__name(async (ctx, body) => {
85
- const apiHeaders = getApiHeaders ? getApiHeaders(ctx) : {};
86
- const runRequest = /* @__PURE__ */__name(async transport => {
87
- await transport.handleRequest(ctx.req, ctx.res, body);
88
- ctx.respond = false;
89
- }, "runRequest");
90
- if (isStateful && sharedTransport) {
91
- if (needsContext) {
92
- await requestContextStore.run({
93
- apiBaseUrl,
94
- apiHeaders
95
- }, () => {
96
- return runRequest(sharedTransport);
97
- });
98
- } else {
99
- await runRequest(sharedTransport);
100
- }
101
- } else {
102
- await enqueueStateless(async () => {
103
- const transport = new StreamableHTTPServerTransport({
104
- sessionIdGenerator: void 0,
105
- enableJsonResponse: true
106
- });
107
- try {
108
- await server.connect(transport);
109
- if (needsContext) {
110
- await requestContextStore.run({
111
- apiBaseUrl,
112
- apiHeaders
113
- }, () => {
114
- return runRequest(transport);
115
- });
116
- } else {
117
- await runRequest(transport);
118
- }
119
- } finally {
120
- await transport.close();
121
- }
122
- });
123
- }
124
- }, "handleWithContext");
125
- router.post(path, async ctx => {
126
- try {
127
- await handleWithContext(ctx, ctx.request.body);
128
- } catch (error) {
129
- if (!ctx.res.headersSent) {
130
- ctx.status = 500;
131
- ctx.body = {
132
- error: error instanceof Error ? error.message : "Internal server error"
133
- };
134
- }
135
- }
136
- });
137
- router.delete(path, async ctx => {
138
- try {
139
- await handleWithContext(ctx);
140
- } catch (error) {
141
- if (!ctx.res.headersSent) {
142
- ctx.status = 500;
143
- ctx.body = {
144
- error: error instanceof Error ? error.message : "Internal server error"
145
- };
146
- }
147
- }
148
- });
149
- return router;
150
- }, "createMcpRouter");
151
- var rawSchemaRegistryMap = /* @__PURE__ */new WeakMap();
152
- var patchedServerSet = /* @__PURE__ */new WeakSet();
153
- var registerToolFromSchema = /* @__PURE__ */__name((server, params) => {
154
- const {
155
- name,
156
- description,
157
- inputSchema = {
158
- type: "object",
159
- properties: {}
160
- },
161
- handler
162
- } = params;
163
- if (!rawSchemaRegistryMap.has(server)) {
164
- rawSchemaRegistryMap.set(server, /* @__PURE__ */new Map());
165
- }
166
- const registry = rawSchemaRegistryMap.get(server);
167
- registry.set(name, inputSchema);
168
- server.registerTool(name, {
169
- description,
170
- inputSchema: z.record(z.string(), z.unknown())
171
- }, async args => {
172
- return handler(args);
173
- });
174
- if (!patchedServerSet.has(server)) {
175
- patchedServerSet.add(server);
176
- const rawServer = server.server;
177
- const origHandler = rawServer?._requestHandlers?.get("tools/list");
178
- if (!origHandler && process.env.NODE_ENV !== "production") {
179
- console.warn("[registerToolFromSchema] Could not patch tools/list \u2014 internal MCP SDK structure may have changed. The tool will still be callable, but tools/list may return a Zod-derived schema instead of the verbatim JSON Schema.");
180
- }
181
- if (origHandler) {
182
- rawServer._requestHandlers.set("tools/list", async (rawRequest, extra) => {
183
- const result = await origHandler(rawRequest, extra);
184
- const schemas = rawSchemaRegistryMap.get(server);
185
- if (!schemas) {
186
- return result;
187
- }
188
- return {
189
- ...result,
190
- tools: result.tools.map(tool => {
191
- const raw = schemas.get(tool.name);
192
- if (raw !== void 0) {
193
- return {
194
- ...tool,
195
- inputSchema: raw
196
- };
197
- }
198
- return tool;
199
- })
200
- };
201
- });
202
- }
203
- }
204
- }, "registerToolFromSchema");
205
- export { McpServer, apiCall, createMcpRouter, registerToolFromSchema, z2 as z };