@tupik/mcp 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Carlos Alberto Barbosa Stenzel / Tupik Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
1
+ # @tupik/mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Turns a **Tupik** app into an MCP server (Streamable HTTP, JSON-RPC 2.0, stateless). The routes you opt in become
4
+ tools whose input schema comes from the route contract. A tool call is a request to `app.fetch`, so the same access
5
+ rules, principal, validation and response shaping apply; classified `pii`/`health` fields are removed before the
6
+ result reaches the model unless you release them.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ npm install @tupik/mcp @tupik/core
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```ts
17
+ import { createApp, createModule } from '@tupik/core';
18
+ import { createMcpServer } from '@tupik/mcp';
19
+
20
+ const patients = createModule('/patients').get('/:id', {
21
+ access: { owner: (ctx) => findPatient(ctx.params.id)?.doctorId },
22
+ tags: ['mcp'], // opt-in: only tagged routes become tools
23
+ schema: { response: { 200: Patient } }, // Patient classifies email as pii, diagnosis as health
24
+ handler: (ctx) => findPatient(ctx.params.id),
25
+ });
26
+ const app = createApp({ authenticate: bearerUser }).register(patients);
27
+
28
+ const mcp = createMcpServer(app, { name: 'clinic', version: '1.0.0' });
29
+ // Workers: export default { fetch: (request) => new URL(request.url).pathname === '/mcp' ? mcp.fetch(request) : app.fetch(request) };
30
+ ```
31
+
32
+ `tools/call { name: 'getPatientsById', arguments: { params: { id: 'p1' } } }` runs `GET /patients/p1` with the
33
+ `authorization` and `cookie` headers of the MCP request. No principal gets `UNAUTHORIZED`, someone else's patient
34
+ gets `NOT_FOUND`, and the doctor gets the record without `email` and `diagnosis` (listed in `_meta['tupik/removed']`).
35
+
36
+ ## Options
37
+
38
+ | Option | Default | Purpose |
39
+ | --- | --- | --- |
40
+ | `tools` | `{ tag: 'mcp' }` | Routes tagged with `tag`, or a list of `'METHOD /path'` (unknown entries throw) |
41
+ | `allowDataClasses` | `[]` | Classes the model may receive (`'pii'`, `'health'`); `secret` is always removed |
42
+ | `forwardHeaders` | `['authorization', 'cookie']` | Headers copied to the app call |
43
+ | `allowedOrigins` | `[]` | `Origin` values accepted (DNS rebinding guard); requests without `Origin` pass |
44
+ | `name`, `version`, `instructions` | `tupik`, `0.0.0` | Sent on `initialize` |
45
+ | `schemaConverter` | none | Standard Schema to JSON Schema for the tool input schemas |
46
+
47
+ Protocol: `initialize` (versions `2025-06-18`, `2025-03-26`), `ping`, `tools/list`, `tools/call`; notifications get
48
+ 202; batches, GET streams and sessions are not offered (405 / error). No SDK dependency: it runs wherever `fetch` does.
49
+
50
+ ## License
51
+
52
+ MIT
@@ -0,0 +1,88 @@
1
+ import { RouteSchema, RouteMeta, DataClass } from '@tupik/core';
2
+ import { JsonSchemaObject, SchemaConverter } from '@tupik/openapi';
3
+
4
+ /** A route as `app.routes` exposes it (a `CompiledRoute` fits). */
5
+ interface McpRoute {
6
+ readonly method: string;
7
+ readonly path: string;
8
+ readonly schema?: RouteSchema | undefined;
9
+ readonly meta: RouteMeta;
10
+ }
11
+ interface McpToolAnnotations {
12
+ readonly title: string;
13
+ readonly readOnlyHint: boolean;
14
+ readonly destructiveHint: boolean;
15
+ readonly idempotentHint: boolean;
16
+ readonly openWorldHint: false;
17
+ }
18
+ /** A tool as `tools/list` describes it. */
19
+ interface McpTool {
20
+ readonly name: string;
21
+ readonly description: string;
22
+ readonly inputSchema: JsonSchemaObject;
23
+ readonly annotations: McpToolAnnotations;
24
+ }
25
+
26
+ /**
27
+ * The JSON-RPC 2.0 slice MCP's Streamable HTTP transport needs: one request
28
+ * per POST (batches were removed in 2025-06-18), notifications answered with
29
+ * 202, plain `application/json` responses (no SSE stream).
30
+ */
31
+ /** Newest first; `initialize` echoes the client's version when listed, else offers the first. */
32
+ declare const MCP_PROTOCOL_VERSIONS: readonly ["2025-06-18", "2025-03-26"];
33
+ declare const JSON_RPC_ERRORS: {
34
+ readonly parse: -32700;
35
+ readonly invalidRequest: -32600;
36
+ readonly methodNotFound: -32601;
37
+ readonly invalidParams: -32602;
38
+ readonly internal: -32603;
39
+ };
40
+ /** Raised by a method handler; becomes a JSON-RPC error response. */
41
+ declare class JsonRpcError extends Error {
42
+ readonly code: number;
43
+ constructor(code: number, message: string);
44
+ }
45
+
46
+ /** The app slice the server needs (a `TupikApp` fits). */
47
+ interface McpApp {
48
+ readonly routes: readonly McpRoute[];
49
+ fetch(request: Request): Promise<Response>;
50
+ }
51
+ interface McpServerOptions {
52
+ /** `serverInfo` sent on `initialize`. Default `tupik` / `0.0.0`. */
53
+ readonly name?: string;
54
+ readonly version?: string;
55
+ /** Free text for the model on `initialize`. */
56
+ readonly instructions?: string;
57
+ /**
58
+ * Routes exposed as tools (opt-in): routes tagged with `tag` (default
59
+ * `{ tag: 'mcp' }`, i.e. `tags: ['mcp']` on the route) or a list of `'METHOD /path'`.
60
+ */
61
+ readonly tools?: {
62
+ readonly tag: string;
63
+ } | readonly string[];
64
+ /** Classes the model may receive. Default none: `pii` and `health` fields are removed; `secret` always is. */
65
+ readonly allowDataClasses?: readonly Exclude<DataClass, 'secret'>[];
66
+ /** Request headers copied to the app call (so `authenticate` sees them). Default `authorization`, `cookie`. */
67
+ readonly forwardHeaders?: readonly string[];
68
+ /** Allowed `Origin` values (DNS rebinding guard). Requests without `Origin` pass; others need a listed origin. */
69
+ readonly allowedOrigins?: readonly string[];
70
+ /** Standard Schema → JSON Schema for the tool input schemas. */
71
+ readonly schemaConverter?: SchemaConverter;
72
+ }
73
+ interface McpServer {
74
+ /** Streamable HTTP endpoint: mount it on a route (`POST /mcp`) or serve it directly. */
75
+ fetch(request: Request): Promise<Response>;
76
+ readonly tools: readonly McpTool[];
77
+ }
78
+ /**
79
+ * MCP server (Streamable HTTP, JSON-RPC 2.0, stateless) over a Tupik app.
80
+ * Opted-in routes become tools; a call is a request to `app.fetch`, so access
81
+ * rules, the principal (from the forwarded headers), validation and response
82
+ * shaping all apply. Classified `pii`/`health` fields are removed from the
83
+ * result unless `allowDataClasses` lists them.
84
+ */
85
+ declare function createMcpServer(app: McpApp, options?: McpServerOptions): McpServer;
86
+
87
+ export { JSON_RPC_ERRORS, JsonRpcError, MCP_PROTOCOL_VERSIONS, createMcpServer };
88
+ export type { McpApp, McpRoute, McpServer, McpServerOptions, McpTool, McpToolAnnotations };
@@ -0,0 +1,88 @@
1
+ import { RouteSchema, RouteMeta, DataClass } from '@tupik/core';
2
+ import { JsonSchemaObject, SchemaConverter } from '@tupik/openapi';
3
+
4
+ /** A route as `app.routes` exposes it (a `CompiledRoute` fits). */
5
+ interface McpRoute {
6
+ readonly method: string;
7
+ readonly path: string;
8
+ readonly schema?: RouteSchema | undefined;
9
+ readonly meta: RouteMeta;
10
+ }
11
+ interface McpToolAnnotations {
12
+ readonly title: string;
13
+ readonly readOnlyHint: boolean;
14
+ readonly destructiveHint: boolean;
15
+ readonly idempotentHint: boolean;
16
+ readonly openWorldHint: false;
17
+ }
18
+ /** A tool as `tools/list` describes it. */
19
+ interface McpTool {
20
+ readonly name: string;
21
+ readonly description: string;
22
+ readonly inputSchema: JsonSchemaObject;
23
+ readonly annotations: McpToolAnnotations;
24
+ }
25
+
26
+ /**
27
+ * The JSON-RPC 2.0 slice MCP's Streamable HTTP transport needs: one request
28
+ * per POST (batches were removed in 2025-06-18), notifications answered with
29
+ * 202, plain `application/json` responses (no SSE stream).
30
+ */
31
+ /** Newest first; `initialize` echoes the client's version when listed, else offers the first. */
32
+ declare const MCP_PROTOCOL_VERSIONS: readonly ["2025-06-18", "2025-03-26"];
33
+ declare const JSON_RPC_ERRORS: {
34
+ readonly parse: -32700;
35
+ readonly invalidRequest: -32600;
36
+ readonly methodNotFound: -32601;
37
+ readonly invalidParams: -32602;
38
+ readonly internal: -32603;
39
+ };
40
+ /** Raised by a method handler; becomes a JSON-RPC error response. */
41
+ declare class JsonRpcError extends Error {
42
+ readonly code: number;
43
+ constructor(code: number, message: string);
44
+ }
45
+
46
+ /** The app slice the server needs (a `TupikApp` fits). */
47
+ interface McpApp {
48
+ readonly routes: readonly McpRoute[];
49
+ fetch(request: Request): Promise<Response>;
50
+ }
51
+ interface McpServerOptions {
52
+ /** `serverInfo` sent on `initialize`. Default `tupik` / `0.0.0`. */
53
+ readonly name?: string;
54
+ readonly version?: string;
55
+ /** Free text for the model on `initialize`. */
56
+ readonly instructions?: string;
57
+ /**
58
+ * Routes exposed as tools (opt-in): routes tagged with `tag` (default
59
+ * `{ tag: 'mcp' }`, i.e. `tags: ['mcp']` on the route) or a list of `'METHOD /path'`.
60
+ */
61
+ readonly tools?: {
62
+ readonly tag: string;
63
+ } | readonly string[];
64
+ /** Classes the model may receive. Default none: `pii` and `health` fields are removed; `secret` always is. */
65
+ readonly allowDataClasses?: readonly Exclude<DataClass, 'secret'>[];
66
+ /** Request headers copied to the app call (so `authenticate` sees them). Default `authorization`, `cookie`. */
67
+ readonly forwardHeaders?: readonly string[];
68
+ /** Allowed `Origin` values (DNS rebinding guard). Requests without `Origin` pass; others need a listed origin. */
69
+ readonly allowedOrigins?: readonly string[];
70
+ /** Standard Schema → JSON Schema for the tool input schemas. */
71
+ readonly schemaConverter?: SchemaConverter;
72
+ }
73
+ interface McpServer {
74
+ /** Streamable HTTP endpoint: mount it on a route (`POST /mcp`) or serve it directly. */
75
+ fetch(request: Request): Promise<Response>;
76
+ readonly tools: readonly McpTool[];
77
+ }
78
+ /**
79
+ * MCP server (Streamable HTTP, JSON-RPC 2.0, stateless) over a Tupik app.
80
+ * Opted-in routes become tools; a call is a request to `app.fetch`, so access
81
+ * rules, the principal (from the forwarded headers), validation and response
82
+ * shaping all apply. Classified `pii`/`health` fields are removed from the
83
+ * result unless `allowDataClasses` lists them.
84
+ */
85
+ declare function createMcpServer(app: McpApp, options?: McpServerOptions): McpServer;
86
+
87
+ export { JSON_RPC_ERRORS, JsonRpcError, MCP_PROTOCOL_VERSIONS, createMcpServer };
88
+ export type { McpApp, McpRoute, McpServer, McpServerOptions, McpTool, McpToolAnnotations };
package/dist/index.mjs ADDED
@@ -0,0 +1,260 @@
1
+ import { operationIdOf, routeSchemaConverter } from '@tupik/openapi';
2
+
3
+ const MCP_PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26"];
4
+ const JSON_RPC_ERRORS = {
5
+ parse: -32700,
6
+ invalidRequest: -32600,
7
+ methodNotFound: -32601,
8
+ invalidParams: -32602,
9
+ internal: -32603
10
+ };
11
+ class JsonRpcError extends Error {
12
+ code;
13
+ constructor(code, message) {
14
+ super(message);
15
+ this.name = "JsonRpcError";
16
+ this.code = code;
17
+ }
18
+ }
19
+ const JSON_HEADERS = { "content-type": "application/json" };
20
+ function jsonRpcResult(id, result) {
21
+ return new Response(JSON.stringify({ jsonrpc: "2.0", id, result }), { status: 200, headers: JSON_HEADERS });
22
+ }
23
+ function jsonRpcError(id, code, message, status = 200) {
24
+ return new Response(JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } }), { status, headers: JSON_HEADERS });
25
+ }
26
+ function isRecord$1(value) {
27
+ return typeof value === "object" && value !== null && !Array.isArray(value);
28
+ }
29
+ function parseMessage(text) {
30
+ let message;
31
+ try {
32
+ message = JSON.parse(text);
33
+ } catch {
34
+ return { kind: "invalid", response: jsonRpcError(null, JSON_RPC_ERRORS.parse, "Parse error: the body is not JSON", 400) };
35
+ }
36
+ if (Array.isArray(message)) {
37
+ return { kind: "invalid", response: jsonRpcError(null, JSON_RPC_ERRORS.invalidRequest, "Batches are not supported: send one JSON-RPC message per request", 400) };
38
+ }
39
+ if (!isRecord$1(message) || message["jsonrpc"] !== "2.0") {
40
+ return { kind: "invalid", response: jsonRpcError(null, JSON_RPC_ERRORS.invalidRequest, "Invalid request: expected a JSON-RPC 2.0 object", 400) };
41
+ }
42
+ const id = message["id"];
43
+ if (typeof message["method"] !== "string" || id === void 0 || id === null) return { kind: "notification" };
44
+ if (typeof id !== "string" && typeof id !== "number") {
45
+ return { kind: "invalid", response: jsonRpcError(null, JSON_RPC_ERRORS.invalidRequest, "Invalid request: id must be a string or a number", 400) };
46
+ }
47
+ return { kind: "request", request: { jsonrpc: "2.0", id, method: message["method"], params: message["params"] } };
48
+ }
49
+
50
+ const METHOD_HINTS = {
51
+ GET: { readOnly: true, destructive: false, idempotent: true },
52
+ HEAD: { readOnly: true, destructive: false, idempotent: true },
53
+ OPTIONS: { readOnly: true, destructive: false, idempotent: true },
54
+ POST: { readOnly: false, destructive: false, idempotent: false },
55
+ PUT: { readOnly: false, destructive: true, idempotent: true },
56
+ PATCH: { readOnly: false, destructive: true, idempotent: false },
57
+ DELETE: { readOnly: false, destructive: true, idempotent: true }
58
+ };
59
+ const BODY_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
60
+ function isRecord(value) {
61
+ return typeof value === "object" && value !== null && !Array.isArray(value);
62
+ }
63
+ function pathParams(path) {
64
+ return path.split("/").filter((segment) => segment.startsWith(":")).map((segment) => segment.slice(1));
65
+ }
66
+ function inputSchemaOf(route, params, converter) {
67
+ const convert = routeSchemaConverter(route, converter, "ignore");
68
+ const schema = route.schema;
69
+ const properties = {};
70
+ const required = [];
71
+ if (params.length > 0) {
72
+ const declared = schema?.params === void 0 ? {} : convert(schema.params, "params");
73
+ properties["params"] = isRecord(declared["properties"]) ? { ...declared, required: params } : { type: "object", properties: Object.fromEntries(params.map((name) => [name, { type: "string" }])), required: [...params] };
74
+ required.push("params");
75
+ }
76
+ if (schema?.query !== void 0) {
77
+ const query = convert(schema.query, "query");
78
+ properties["query"] = Object.keys(query).length === 0 ? { type: "object" } : query;
79
+ if (Array.isArray(query["required"]) && query["required"].length > 0) required.push("query");
80
+ }
81
+ if (schema?.body !== void 0) {
82
+ properties["body"] = convert(schema.body, "body");
83
+ required.push("body");
84
+ } else if (BODY_METHODS.has(route.method)) {
85
+ properties["body"] = {};
86
+ }
87
+ return { type: "object", properties, required, additionalProperties: false };
88
+ }
89
+ function bindTool(route, converter) {
90
+ const params = pathParams(route.path);
91
+ const hints = METHOD_HINTS[route.method] ?? METHOD_HINTS["POST"];
92
+ const label = `${route.method} ${route.path}`;
93
+ return {
94
+ route,
95
+ params,
96
+ tool: {
97
+ name: operationIdOf(route),
98
+ description: `${label} (access: ${route.meta.access}). Arguments: params (path), query and body as the API contract declares them.`,
99
+ inputSchema: inputSchemaOf(route, params, converter),
100
+ annotations: {
101
+ title: label,
102
+ readOnlyHint: hints?.readOnly ?? false,
103
+ destructiveHint: hints?.destructive ?? true,
104
+ idempotentHint: hints?.idempotent ?? false,
105
+ openWorldHint: false
106
+ }
107
+ }
108
+ };
109
+ }
110
+ function invalid(message) {
111
+ return new JsonRpcError(JSON_RPC_ERRORS.invalidParams, message);
112
+ }
113
+ function callTarget(binding, args) {
114
+ if (args !== void 0 && !isRecord(args)) throw invalid(`${binding.tool.name}: arguments must be an object { params?, query?, body? }`);
115
+ const params = args?.["params"];
116
+ if (params !== void 0 && !isRecord(params)) throw invalid(`${binding.tool.name}: arguments.params must be an object`);
117
+ const path = binding.route.path.split("/").map((segment) => {
118
+ if (!segment.startsWith(":")) return segment;
119
+ const value = params?.[segment.slice(1)];
120
+ if (typeof value !== "string" && typeof value !== "number") throw invalid(`${binding.tool.name}: arguments.params.${segment.slice(1)} is required (string)`);
121
+ return encodeURIComponent(String(value));
122
+ }).join("/");
123
+ const query = args?.["query"];
124
+ if (query !== void 0 && !isRecord(query)) throw invalid(`${binding.tool.name}: arguments.query must be an object`);
125
+ const search = new URLSearchParams();
126
+ for (const [key, value] of Object.entries(query ?? {})) {
127
+ for (const item of Array.isArray(value) ? value : [value]) if (item !== void 0 && item !== null) search.append(key, String(item));
128
+ }
129
+ const text = search.toString();
130
+ const body = args?.["body"];
131
+ return { path: text === "" ? path : `${path}?${text}`, body: body === void 0 ? void 0 : JSON.stringify(body) };
132
+ }
133
+ function omit(value, path, removed) {
134
+ if (Array.isArray(value)) return value.map((item) => omit(item, path, removed));
135
+ const [head, ...rest] = path;
136
+ if (head === void 0 || !isRecord(value) || !Object.hasOwn(value, head)) return value;
137
+ if (rest.length === 0) {
138
+ removed.found = true;
139
+ const { [head]: _dropped, ...kept } = value;
140
+ return kept;
141
+ }
142
+ return { ...value, [head]: omit(value[head], rest, removed) };
143
+ }
144
+ const MODEL_CLASSES = ["secret", "health", "pii"];
145
+ function redact(route, status, data, allowed) {
146
+ const classes = route.meta.dataClasses.response?.[status] ?? {};
147
+ const removed = [];
148
+ let value = data;
149
+ for (const dataClass of MODEL_CLASSES) {
150
+ if (dataClass !== "secret" && allowed.has(dataClass)) continue;
151
+ for (const path of classes[dataClass] ?? []) {
152
+ const flag = { found: false };
153
+ value = omit(value, path.split("."), flag);
154
+ if (flag.found) removed.push(`${path} (${dataClass})`);
155
+ }
156
+ }
157
+ return { data: value, removed: removed.sort() };
158
+ }
159
+
160
+ function selectRoutes(app, selection) {
161
+ if (selection === void 0 || !Array.isArray(selection)) {
162
+ const tag = selection?.tag ?? "mcp";
163
+ return app.routes.filter((route) => route.meta.tags.has(tag));
164
+ }
165
+ return selection.map((key) => {
166
+ const route = app.routes.find((candidate) => `${candidate.method} ${candidate.path}` === key);
167
+ if (route === void 0) throw new Error(`@tupik/mcp: ${key} is not a route of the app; list routes as 'METHOD /path' (e.g. 'GET /users/:id')`);
168
+ return route;
169
+ });
170
+ }
171
+ function negotiate(params) {
172
+ const requested = params?.protocolVersion;
173
+ return MCP_PROTOCOL_VERSIONS.includes(requested) ? String(requested) : MCP_PROTOCOL_VERSIONS[0];
174
+ }
175
+ async function readBody(response) {
176
+ const text = await response.text();
177
+ if (text === "") return null;
178
+ try {
179
+ return JSON.parse(text);
180
+ } catch {
181
+ return text;
182
+ }
183
+ }
184
+ function createMcpServer(app, options = {}) {
185
+ const bindings = /* @__PURE__ */ new Map();
186
+ for (const route of selectRoutes(app, options.tools)) {
187
+ const binding = bindTool(route, options.schemaConverter);
188
+ bindings.set(binding.tool.name, binding);
189
+ }
190
+ const tools = [...bindings.values()].map((binding) => binding.tool);
191
+ const allowed = new Set(options.allowDataClasses ?? []);
192
+ const forward = (options.forwardHeaders ?? ["authorization", "cookie"]).map((name) => name.toLowerCase());
193
+ const origins = new Set(options.allowedOrigins ?? []);
194
+ async function callTool(request, params) {
195
+ const name = params?.name;
196
+ const binding = typeof name === "string" ? bindings.get(name) : void 0;
197
+ if (binding === void 0) throw new JsonRpcError(JSON_RPC_ERRORS.invalidParams, `Unknown tool ${JSON.stringify(name)}; call tools/list for the available tools`);
198
+ const target = callTarget(binding, params.arguments);
199
+ const headers = new Headers();
200
+ for (const header of forward) {
201
+ const value = request.headers.get(header);
202
+ if (value !== null) headers.set(header, value);
203
+ }
204
+ if (target.body !== void 0) headers.set("content-type", "application/json");
205
+ const response = await app.fetch(new Request(new URL(target.path, request.url), {
206
+ method: binding.route.method,
207
+ headers,
208
+ ...target.body === void 0 ? {} : { body: target.body }
209
+ }));
210
+ const { data, removed } = redact(binding.route, response.status, await readBody(response), allowed);
211
+ const result = {
212
+ content: [{ type: "text", text: JSON.stringify(data) }],
213
+ isError: response.status >= 400
214
+ };
215
+ if (typeof data === "object" && data !== null && !Array.isArray(data)) result["structuredContent"] = data;
216
+ if (removed.length > 0) result["_meta"] = { "tupik/removed": removed };
217
+ return result;
218
+ }
219
+ const METHODS = {
220
+ initialize: (_request, params) => ({
221
+ protocolVersion: negotiate(params),
222
+ capabilities: { tools: { listChanged: false } },
223
+ serverInfo: { name: options.name ?? "tupik", version: options.version ?? "0.0.0" },
224
+ ...options.instructions === void 0 ? {} : { instructions: options.instructions }
225
+ }),
226
+ ping: () => ({}),
227
+ "tools/list": () => ({ tools }),
228
+ "tools/call": callTool
229
+ };
230
+ async function dispatch(request, message) {
231
+ const method = Object.hasOwn(METHODS, message.method) ? METHODS[message.method] : void 0;
232
+ if (method === void 0) return jsonRpcError(message.id, JSON_RPC_ERRORS.methodNotFound, `Method not found: ${message.method}`);
233
+ try {
234
+ return jsonRpcResult(message.id, await method(request, message.params));
235
+ } catch (error) {
236
+ if (error instanceof JsonRpcError) return jsonRpcError(message.id, error.code, error.message);
237
+ return jsonRpcError(message.id, JSON_RPC_ERRORS.internal, "Internal error");
238
+ }
239
+ }
240
+ return {
241
+ tools,
242
+ async fetch(request) {
243
+ const origin = request.headers.get("origin");
244
+ if (origin !== null && !origins.has(origin)) {
245
+ return jsonRpcError(null, JSON_RPC_ERRORS.invalidRequest, `Origin ${origin} is not allowed: add it to createMcpServer({ allowedOrigins })`, 403);
246
+ }
247
+ if (request.method !== "POST") return new Response(null, { status: 405, headers: { allow: "POST" } });
248
+ const version = request.headers.get("mcp-protocol-version");
249
+ if (version !== null && !MCP_PROTOCOL_VERSIONS.includes(version)) {
250
+ return jsonRpcError(null, JSON_RPC_ERRORS.invalidRequest, `Unsupported MCP-Protocol-Version ${version}`, 400);
251
+ }
252
+ const parsed = parseMessage(await request.text());
253
+ if (parsed.kind === "invalid") return parsed.response;
254
+ if (parsed.kind === "notification") return new Response(null, { status: 202 });
255
+ return dispatch(request, parsed.request);
256
+ }
257
+ };
258
+ }
259
+
260
+ export { JSON_RPC_ERRORS, JsonRpcError, MCP_PROTOCOL_VERSIONS, createMcpServer };
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@tupik/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "MCP server (Streamable HTTP, JSON-RPC 2.0) generated from a Tupik app: opt-in routes become tools that run through the app's own access rules, with pii/health fields removed before they reach the model.",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "tupik",
8
+ "typescript",
9
+ "web-framework",
10
+ "mcp",
11
+ "model-context-protocol",
12
+ "ai-agents",
13
+ "json-rpc"
14
+ ],
15
+ "homepage": "https://github.com/CodeHamper/tupikjs/tree/main/packages/mcp#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/CodeHamper/tupikjs.git",
19
+ "directory": "packages/mcp"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/CodeHamper/tupikjs/issues"
23
+ },
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "files": [
30
+ "dist"
31
+ ],
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/index.d.ts",
35
+ "import": "./dist/index.mjs"
36
+ }
37
+ },
38
+ "engines": {
39
+ "node": ">=22.12"
40
+ },
41
+ "dependencies": {
42
+ "@tupik/core": "^1.0.0",
43
+ "@tupik/openapi": "^1.0.0"
44
+ },
45
+ "devDependencies": {
46
+ "typescript": "^5.6.0",
47
+ "unbuild": "^3.0.0",
48
+ "vitest": "^2.1.0"
49
+ },
50
+ "scripts": {
51
+ "build": "unbuild",
52
+ "typecheck": "tsc --noEmit",
53
+ "test": "vitest run"
54
+ }
6
55
  }