@webda/mcp 0.0.0-stage → 4.0.0-beta.3

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,166 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
166
+
package/README.md CHANGED
@@ -1,3 +1,169 @@
1
- # Temporary Holding Version
1
+ # @webda/mcp module
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
+ This module is part of Webda Application Framework that allows you to quickly develop applications with all modern prerequisites: Security, Extensibility, GraphQL, REST, CloudNative [https://webda.io](https://webda.io)
4
+
5
+ <img src="https://webda.io/images/webda.svg" width="128" />
6
+
7
+ ![CI](https://github.com/loopingz/webda.io/workflows/CI/badge.svg)
8
+
9
+ [![Join the chat at https://gitter.im/loopingz/webda](https://badges.gitter.im/loopingz/webda.svg)](https://gitter.im/loopingz/webda?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
10
+ [![codecov](https://codecov.io/gh/loopingz/webda.io/branch/main/graph/badge.svg?token=8N9DNM3K3O)](https://codecov.io/gh/loopingz/webda.io)
11
+ [![SonarCloud.io](https://sonarcloud.io/api/project_badges/measure?project=loopingz_webda.io&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=loopingz_webda.io)
12
+ ![CodeQL](https://github.com/loopingz/webda.io/workflows/CodeQL/badge.svg)
13
+
14
+ <!-- README_HEADER -->
15
+
16
+ # @webda/mcp
17
+
18
+ > Model Context Protocol transport for Webda — exposes registered operations as MCP tools and models as MCP resources, over Streamable HTTP and stdio.
19
+
20
+ ## When to use it
21
+
22
+ - You want AI assistants (Claude Code, Claude Desktop, any MCP client) to call your Webda operations as tools.
23
+ - You want models readable as MCP resources through `webda://{Model}/{pk...}` URIs.
24
+ - You want the same permissions as your REST API: each caller only sees and runs what their session allows.
25
+
26
+ ### What it exposes
27
+
28
+ - **Tools**: every non-hidden operation, the tool name being the operation id (for example `Post.Get`, `Posts.Query`, `User.Login`).
29
+ - **Resources**: models with a `{Model}.Get` operation, as `webda://{Model}/{pk...}` resource templates (for example `webda://Post/{slug}`).
30
+ - **Progress**: `AsyncGenerator` operations stream their chunks as MCP progress notifications.
31
+ - **Truncated outputs**: tool outputs larger than `maxOutputBytes` are truncated with a notice and returned with `isError: true`.
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pnpm add @webda/mcp
37
+ ```
38
+
39
+ ## Configuration
40
+
41
+ ```jsonc
42
+ {
43
+ "services": {
44
+ "mcp": {
45
+ "type": "Webda/McpService",
46
+ "url": "/mcp", // HTTP endpoint; false disables HTTP (stdio only)
47
+ "operations": ["*", "!User.Delete"], // standard OperationsTransport filter
48
+ "resources": { "models": ["*"] }, // false disables resources; model ids or "*"
49
+ "sessionTimeout": 1800, // seconds of inactivity before an MCP session is evicted
50
+ "allowedOrigins": [], // extra Origin values accepted besides the request host
51
+ "allowedHosts": ["localhost", "127.0.0.1", "::1"], // Host header hostnames accepted (any port); "*" disables the check
52
+ "maxSessions": 1000, // cap on open MCP HTTP sessions; at the cap the least recently used one is closed
53
+ "maxOutputBytes": 1048576 // larger tool/resource outputs are truncated with a notice
54
+ // "serverName": "my-app", // defaults to the application package name
55
+ // "serverVersion": "1.0.0", // defaults to the application package version
56
+ // "stdio": { "user": "<userId>" }, // default --user for `webda mcp`
57
+ // "authenticator": "myAuthenticator" // service implementing McpAuthenticator; default uses the Webda session
58
+ }
59
+ }
60
+ }
61
+ ```
62
+
63
+ | Parameter | Type | Default | Description |
64
+ |---|---|---|---|
65
+ | `url` | string \| false | `"/mcp"` | HTTP endpoint; `false` disables HTTP (stdio only) |
66
+ | `operations` | string[] | `["*"]` | Operation filter, with `!` for exclusions |
67
+ | `resources` | `{ models: string[] }` \| false | `{ "models": ["*"] }` | Models exposed as resources; `false` disables resources |
68
+ | `sessionTimeout` | number | `1800` | Seconds of inactivity before an MCP session is evicted |
69
+ | `allowedOrigins` | string[] | `[]` | Extra `Origin` values accepted besides the request host |
70
+ | `allowedHosts` | string[] | `["localhost", "127.0.0.1", "::1"]` | Hostnames accepted on the `Host` header (any port); `"*"` disables the check |
71
+ | `maxSessions` | number | `1000` | Cap on open HTTP sessions; at the cap a new `initialize` closes the least recently used session, whose next request gets `404` (clients then re-initialize) |
72
+ | `maxOutputBytes` | number | `1048576` | Larger tool/resource outputs are truncated with a notice |
73
+ | `serverName` | string | application package name | Server name announced to clients |
74
+ | `serverVersion` | string | application package version | Server version announced to clients |
75
+ | `stdio.user` | string | none | Default `--user` for `webda mcp` |
76
+ | `authenticator` | string | none | Name of a service implementing `McpAuthenticator`; the default uses the Webda session |
77
+
78
+ > **Remote deployments must set `allowedHosts`.** The Host header is checked on every HTTP request as DNS-rebinding protection: unless your public hostname(s) are listed (or the value is `"*"`), every request gets `403 Host not allowed`.
79
+ >
80
+ > **Behind a reverse proxy**, the hostname checked is the `X-Forwarded-Host` header when present, otherwise `Host`. `X-Forwarded-*` headers are only accepted from proxies listed in the HttpServer `trustedProxies` parameter (anything else gets `400` from the HttpServer). A proxy that rewrites `Host` without a trusted `X-Forwarded-Host` gets `403` unless the rewritten hostname is in `allowedHosts`.
81
+
82
+ ## Usage
83
+
84
+ ```bash
85
+ # stdio: Claude launches the application and acts as the given user
86
+ claude mcp add blog -- webda mcp --user <userId>
87
+
88
+ # HTTP: register the endpoint of a running application
89
+ claude mcp add --transport http blog http://localhost:18080/mcp
90
+ ```
91
+
92
+ Use `https://` when the HttpServer serves TLS. With `autoTls` (as in the [blog sample](../../sample-apps/blog-system/README.md#mcp)) the certificate is self-signed: start the MCP client with `NODE_EXTRA_CA_CERTS=<app>/.webda/dev-tls/cert.pem` so it trusts it.
93
+
94
+ `webda mcp` keeps stdout for protocol frames: from the moment the command starts, log lines and any other stdout output go to stderr, whatever `--log-stream` says. Lines logged while the application boots (before the command starts) follow `--log-stream`; its default (`auto`) already sends them to stderr because MCP clients pipe stdout.
95
+
96
+ ### Who is the HTTP caller?
97
+
98
+ The default `SessionAuthenticator` uses Webda's cookie session. MCP clients (Claude Code, the SDK HTTP transports) do not keep cookies, so **HTTP callers are anonymous in practice**: they see and run only the operations anonymous users may call. To act as a user, use stdio (`webda mcp --user <userId>`), or plug a custom authenticator service until OAuth support (planned) lands:
99
+
100
+ ```typescript
101
+ import { Service, Session, WebContext, WebdaError } from "@webda/core";
102
+ import type { McpAuthenticator } from "@webda/mcp";
103
+
104
+ // Your own key lookup (a model query, a secret store...)
105
+ declare function lookupUserForKey(key: string): Promise<string | undefined>;
106
+
107
+ /**
108
+ * Resolve MCP callers from an API key header
109
+ */
110
+ export class ApiKeyAuthenticator extends Service implements McpAuthenticator {
111
+ async authenticate(ctx: WebContext): Promise<Session> {
112
+ const key = ctx.getHttpContext().getUniqueHeader("x-api-key");
113
+ const session = new Session();
114
+ if (key === undefined) {
115
+ return session; // anonymous
116
+ }
117
+ const userId = await lookupUserForKey(key);
118
+ if (!userId) {
119
+ throw new WebdaError.Unauthorized("Invalid API key");
120
+ }
121
+ session.login(userId, userId);
122
+ return session;
123
+ }
124
+ }
125
+ ```
126
+
127
+ ```jsonc
128
+ {
129
+ "services": {
130
+ "apiKeys": { "type": "MyApp/ApiKeyAuthenticator" },
131
+ "mcp": { "type": "Webda/McpService", "authenticator": "apiKeys" }
132
+ }
133
+ }
134
+ ```
135
+
136
+ ### Multiple instances
137
+
138
+ MCP HTTP sessions live in the memory of the instance that created them. When running several instances behind a load balancer, route each client to the same instance (sticky sessions on the `Mcp-Session-Id` header or the client address); a request reaching another instance gets `404 Session not found`.
139
+
140
+ Control how an operation appears to MCP clients:
141
+
142
+ ```typescript
143
+ import { Operation, OperationContext, Service } from "@webda/core";
144
+
145
+ export class PostService extends Service {
146
+ // Not exposed as a tool
147
+ @Operation({ mcp: false })
148
+ async internalCleanup() {}
149
+
150
+ // Exposed with a title and explicit hints
151
+ @Operation({ mcp: { title: "Delete a post", readOnly: false, destructive: true } })
152
+ async deletePost(ctx: OperationContext) {}
153
+ }
154
+ ```
155
+
156
+ ## Security
157
+
158
+ - Permissions apply per caller: an operation is run with the caller's session and `tools/list` is filtered to what that caller may call.
159
+ - HTTP sessions are random ids bound to the user who created them; another user presenting the id is rejected with `403`.
160
+ - Every HTTP request is checked against `allowedHosts` and `Origin` (request host plus `allowedOrigins`) to prevent DNS rebinding.
161
+ - Open sessions are capped by `maxSessions`; at the cap the least recently used session is closed rather than refusing new ones, so nobody can lock the endpoint by opening sessions.
162
+ - With the default authenticator, HTTP callers are anonymous in practice (see [Who is the HTTP caller?](#who-is-the-http-caller)).
163
+ - `webda mcp` over stdio trusts whoever launches it: that process acts with the permissions of `--user` (or anonymous permissions without it).
164
+ - OAuth 2.1 (authorization server and bearer validation) is planned as a second step and will plug in through the `authenticator` hook.
165
+
166
+ ## Reference
167
+
168
+ - Source: [`packages/mcp`](https://github.com/loopingz/webda.io/tree/main/packages/mcp)
169
+ - Design: `docs/superpowers/specs/2026-10-03-webda-mcp-design.md`
package/lib/auth.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import type { Session, WebContext } from "@webda/core";
2
+ /**
3
+ * Resolve the caller of an MCP HTTP request.
4
+ *
5
+ * Implementations throw `WebdaError.Unauthorized` to reject the request.
6
+ * Configure a service implementing it through the McpService `authenticator`
7
+ * parameter; spec 2 adds an OAuth bearer-token implementation.
8
+ */
9
+ export interface McpAuthenticator {
10
+ /**
11
+ * @param ctx - the HTTP request context
12
+ * @returns the caller session
13
+ */
14
+ authenticate(ctx: WebContext): Promise<Session>;
15
+ }
16
+ /**
17
+ * Default authenticator: the Webda session already loaded for the request
18
+ * (cookie session, filled by RequestFilters); anonymous callers get an empty session.
19
+ */
20
+ export declare class SessionAuthenticator implements McpAuthenticator {
21
+ /**
22
+ * @param ctx - the HTTP request context
23
+ * @returns the request session
24
+ */
25
+ authenticate(ctx: WebContext): Promise<Session>;
26
+ }
27
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEvD;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,YAAY,CAAC,GAAG,EAAE,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACjD;AAED;;;GAGG;AACH,qBAAa,oBAAqB,YAAW,gBAAgB;IAC3D;;;OAGG;IACG,YAAY,CAAC,GAAG,EAAE,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,CAEpD;CACF"}
package/lib/auth.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Default authenticator: the Webda session already loaded for the request
3
+ * (cookie session, filled by RequestFilters); anonymous callers get an empty session.
4
+ */
5
+ export class SessionAuthenticator {
6
+ /**
7
+ * @param ctx - the HTTP request context
8
+ * @returns the request session
9
+ */
10
+ async authenticate(ctx) {
11
+ return ctx.getSession();
12
+ }
13
+ }
14
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAiBA;;;GAGG;AACH,MAAM,OAAO,oBAAoB;IAC/B;;;OAGG;IACH,KAAK,CAAC,YAAY,CAAC,GAAe;QAChC,OAAO,GAAG,CAAC,UAAU,EAAE,CAAC;IAC1B,CAAC;CACF"}
@@ -0,0 +1,26 @@
1
+ import type { WebContext } from "@webda/core";
2
+ /**
3
+ * Build a web-standard Request from a Webda context
4
+ * @param ctx - the request context
5
+ * @param body - raw request body (POST only)
6
+ * @param origin - request origin, when HttpContext.getAbsoluteUrl cannot represent it (IPv6 hosts)
7
+ * @returns the Request handed to the SDK transport
8
+ */
9
+ export declare function toRequest(ctx: WebContext, body?: string, origin?: URL): Request;
10
+ /**
11
+ * Write a web-standard Response into a Webda context, streaming the body
12
+ * chunk by chunk (SSE) and stopping when the client disconnects.
13
+ * The returned promise settles when the body is fully written.
14
+ * @param ctx - the request context
15
+ * @param response - the SDK transport response
16
+ */
17
+ export declare function writeResponse(ctx: WebContext, response: Response): Promise<void>;
18
+ /**
19
+ * Answer with a JSON-RPC error body
20
+ * @param ctx - the request context
21
+ * @param status - HTTP status
22
+ * @param code - JSON-RPC error code
23
+ * @param message - error message
24
+ */
25
+ export declare function jsonRpcError(ctx: WebContext, status: number, code: number, message: string): void;
26
+ //# sourceMappingURL=bridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bridge.d.ts","sourceRoot":"","sources":["../src/bridge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE9C;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,GAAG,GAAG,OAAO,CAe/E;AAED;;;;;;GAMG;AACH,wBAAsB,aAAa,CAAC,GAAG,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAwBtF;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAGjG"}
package/lib/bridge.js ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Build a web-standard Request from a Webda context
3
+ * @param ctx - the request context
4
+ * @param body - raw request body (POST only)
5
+ * @param origin - request origin, when HttpContext.getAbsoluteUrl cannot represent it (IPv6 hosts)
6
+ * @returns the Request handed to the SDK transport
7
+ */
8
+ export function toRequest(ctx, body, origin) {
9
+ const http = ctx.getHttpContext();
10
+ const headers = new Headers();
11
+ for (const [name, value] of Object.entries(http.getHeaders())) {
12
+ if (value === undefined)
13
+ continue;
14
+ if (Array.isArray(value)) {
15
+ value.forEach(v => headers.append(name, v));
16
+ }
17
+ else {
18
+ headers.set(name, String(value));
19
+ }
20
+ }
21
+ const method = http.getMethod();
22
+ const uri = http.getUrl();
23
+ const url = origin && !/^\w{1,10}:\/\//.test(uri) ? `${origin.origin}${uri.startsWith("/") ? "" : "/"}${uri}` : http.getAbsoluteUrl();
24
+ return new Request(url, { method, headers, body: method === "POST" ? (body ?? "") : undefined });
25
+ }
26
+ /**
27
+ * Write a web-standard Response into a Webda context, streaming the body
28
+ * chunk by chunk (SSE) and stopping when the client disconnects.
29
+ * The returned promise settles when the body is fully written.
30
+ * @param ctx - the request context
31
+ * @param response - the SDK transport response
32
+ */
33
+ export async function writeResponse(ctx, response) {
34
+ const headers = {};
35
+ response.headers.forEach((value, name) => (headers[name] = value));
36
+ ctx.writeHead(response.status, headers);
37
+ const out = await ctx.getOutputStream();
38
+ if (!response.body) {
39
+ return;
40
+ }
41
+ const reader = response.body.getReader();
42
+ const onClose = () => {
43
+ reader.cancel().catch(() => { });
44
+ };
45
+ out.once?.("close", onClose);
46
+ try {
47
+ for (;;) {
48
+ const { done, value } = await reader.read();
49
+ if (done)
50
+ break;
51
+ out.write(Buffer.from(value));
52
+ }
53
+ }
54
+ catch {
55
+ // client went away; nothing left to write
56
+ }
57
+ finally {
58
+ out.off?.("close", onClose);
59
+ }
60
+ }
61
+ /**
62
+ * Answer with a JSON-RPC error body
63
+ * @param ctx - the request context
64
+ * @param status - HTTP status
65
+ * @param code - JSON-RPC error code
66
+ * @param message - error message
67
+ */
68
+ export function jsonRpcError(ctx, status, code, message) {
69
+ ctx.writeHead(status, { "content-type": "application/json" });
70
+ ctx.write(JSON.stringify({ jsonrpc: "2.0", error: { code, message }, id: null }));
71
+ }
72
+ //# sourceMappingURL=bridge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bridge.js","sourceRoot":"","sources":["../src/bridge.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,GAAe,EAAE,IAAa,EAAE,MAAY;IACpE,MAAM,IAAI,GAAG,GAAG,CAAC,cAAc,EAAE,CAAC;IAClC,MAAM,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC;IAC9B,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC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ADDED
@@ -0,0 +1,10 @@
1
+ export * from "./schema.js";
2
+ export * from "./tools.js";
3
+ export * from "./invoke.js";
4
+ export * from "./resources.js";
5
+ export * from "./auth.js";
6
+ export * from "./server.js";
7
+ export * from "./sessions.js";
8
+ export * from "./bridge.js";
9
+ export * from "./mcpservice.service.js";
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC;AAC9B,cAAc,aAAa,CAAC;AAC5B,cAAc,yBAAyB,CAAC"}
package/lib/index.js ADDED
@@ -0,0 +1,10 @@
1
+ export * from "./schema.js";
2
+ export * from "./tools.js";
3
+ export * from "./invoke.js";
4
+ export * from "./resources.js";
5
+ export * from "./auth.js";
6
+ export * from "./server.js";
7
+ export * from "./sessions.js";
8
+ export * from "./bridge.js";
9
+ export * from "./mcpservice.service.js";
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC;AAC9B,cAAc,aAAa,CAAC;AAC5B,cAAc,yBAAyB,CAAC"}
@@ -0,0 +1,108 @@
1
+ import { Session, SimpleOperationContext } from "@webda/core";
2
+ import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
3
+ import type { ToolEntry } from "./tools.js";
4
+ /**
5
+ * Raised when an MCP client cancels a running operation
6
+ */
7
+ export declare class CancelledError extends Error {
8
+ /**
9
+ * Build the cancellation error
10
+ */
11
+ constructor();
12
+ }
13
+ /**
14
+ * Operation context used for MCP calls: collects AsyncGenerator chunks
15
+ * instead of concatenating them into the output, and stops on cancellation.
16
+ */
17
+ export declare class McpOperationContext extends SimpleOperationContext {
18
+ /**
19
+ * Chunks yielded by a streaming operation
20
+ */
21
+ chunks: unknown[];
22
+ /**
23
+ * Abort signal of the MCP request
24
+ */
25
+ signal?: AbortSignal;
26
+ /**
27
+ * Called for every streamed chunk with its 1-based index
28
+ */
29
+ onChunk?: (chunk: unknown, index: number) => void;
30
+ /**
31
+ * @param output - chunk or result
32
+ * @param encoding - unused for chunks
33
+ * @param cb - unused for chunks
34
+ * @returns true
35
+ */
36
+ write(output: any, encoding?: any, cb?: any): boolean;
37
+ }
38
+ /**
39
+ * Options to run an operation for MCP
40
+ */
41
+ export interface RunOptions {
42
+ /**
43
+ * Session of the caller; permissions are evaluated against it
44
+ */
45
+ session: Session;
46
+ /**
47
+ * Operation input (tool arguments)
48
+ */
49
+ input?: unknown;
50
+ /**
51
+ * Abort signal of the MCP request
52
+ */
53
+ signal?: AbortSignal;
54
+ /**
55
+ * Streaming chunk callback
56
+ */
57
+ onChunk?: (chunk: unknown, index: number) => void;
58
+ }
59
+ /**
60
+ * Build a context holding a session, for permission checks
61
+ * @param session - caller session
62
+ * @returns a context with that session
63
+ */
64
+ export declare function sessionContext(session: Session): SimpleOperationContext;
65
+ /**
66
+ * Run an operation as the caller through core `callOperation`
67
+ * (permission, validation, events, audit and dispatch all apply)
68
+ * @param operationId - operation id
69
+ * @param options - session, input, cancellation and streaming hooks
70
+ * @returns the parsed result, or the chunks when the operation streamed
71
+ */
72
+ export declare function runOperation(operationId: string, options: RunOptions): Promise<{
73
+ value: unknown;
74
+ streamed: boolean;
75
+ }>;
76
+ /**
77
+ * Truncate a string to at most `maxBytes` UTF-8 bytes without cutting a character
78
+ * @param text - the text
79
+ * @param maxBytes - maximum number of bytes kept
80
+ * @returns the (possibly) truncated text, whether it was truncated and the original byte length
81
+ */
82
+ export declare function truncateUtf8(text: string, maxBytes: number): {
83
+ text: string;
84
+ truncated: boolean;
85
+ bytes: number;
86
+ };
87
+ /**
88
+ * Convert an operation result into an MCP tool result.
89
+ *
90
+ * Tools declare no outputSchema (serialized models rarely match their schema exactly),
91
+ * so structuredContent is informative only: the object itself, `{ value }` for scalars
92
+ * and arrays, `{ items }` for streamed chunks, and nothing for void.
93
+ * @param _entry - the tool
94
+ * @param value - operation result
95
+ * @param streamed - whether value is the list of streamed chunks
96
+ * @param maxOutputBytes - truncation threshold for the text content
97
+ * @returns the tool result
98
+ */
99
+ export declare function toToolResult(_entry: ToolEntry, value: unknown, streamed: boolean, maxOutputBytes: number): CallToolResult;
100
+ /**
101
+ * Convert an error into an MCP tool error result.
102
+ * Client errors (4xx) are returned so the agent can correct its input;
103
+ * anything else is logged and masked.
104
+ * @param err - the error
105
+ * @returns the tool error result
106
+ */
107
+ export declare function errorToToolResult(err: unknown): CallToolResult;
108
+ //# sourceMappingURL=invoke.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invoke.d.ts","sourceRoot":"","sources":["../src/invoke.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,OAAO,EAAE,sBAAsB,EAAc,MAAM,aAAa,CAAC;AACzF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AAEzE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C;;GAEG;AACH,qBAAa,cAAe,SAAQ,KAAK;IACvC;;OAEG;IACH,cAGC;CACF;AAED;;;GAGG;AACH,qBAAa,mBAAoB,SAAQ,sBAAsB;IAC7D;;OAEG;IACH,MAAM,EAAE,OAAO,EAAE,CAAM;IACvB;;OAEG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB;;OAEG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,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