@venturekit/mcp 0.0.0-dev.20260608102211

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,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2025 VentureKit Contributors
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,137 @@
1
+ # @venturekit/mcp
2
+
3
+ Transport-agnostic [Model Context Protocol](https://modelcontextprotocol.io) (MCP)
4
+ server primitives for VentureKit apps.
5
+
6
+ The package owns the **protocol core** — a stateless JSON-RPC dispatcher, a typed
7
+ tool registry, and a Zod → JSON-Schema serializer for `tools/list` — plus an
8
+ optional, batteries-included **bearer-token layer**: the `vk_<scope>_<secret>`
9
+ token format, a Postgres-backed token store, and the `mcp_tokens` migration that
10
+ ships _with the package_. App-specific concerns — authentication, rate limiting,
11
+ audit logging, per-call context — are injected through hooks, so any app can
12
+ expose an MCP endpoint (and issue/verify tokens for it) without re-implementing
13
+ the generic parts.
14
+
15
+ It stays dependency-light: `zod` is a **type-only peer dependency**, token hashing
16
+ uses `node:crypto` scrypt (no third-party crypto dep), and the store talks to your
17
+ database through a structural `Querier` (pass `@venturekit/data`'s `query` — no DB
18
+ driver dependency). The dispatcher core itself remains entirely storage-free.
19
+
20
+ ## Why not the official SDK?
21
+
22
+ `@modelcontextprotocol/sdk` is built around long-lived transports/sessions
23
+ (stdio, SSE, streamable HTTP). VentureKit APIs run as **stateless** request →
24
+ response handlers (Lambda / API Gateway), where one HTTP POST carries one
25
+ JSON-RPC message. This package implements exactly that slice — `initialize`,
26
+ `notifications/initialized`, `ping`, `tools/list`, `tools/call` — with no
27
+ session state to manage.
28
+
29
+ ## Usage
30
+
31
+ ```ts
32
+ import { handleMcpRequest, McpError, type McpServerConfig } from '@venturekit/mcp';
33
+ import { z } from 'zod';
34
+
35
+ // 1. Define tools. `run` receives validated args + your per-call context.
36
+ const tools = {
37
+ echo: {
38
+ name: 'echo',
39
+ description: 'Echo a message back.',
40
+ inputSchema: z.object({ message: z.string() }),
41
+ run: async (args: { message: string }, ctx: { tenantId: string }) => ({
42
+ echoed: args.message,
43
+ tenant: ctx.tenantId,
44
+ }),
45
+ },
46
+ };
47
+
48
+ // 2. Wire the host concerns as hooks.
49
+ const config: McpServerConfig<{ tenantId: string }, { tenantId: string }> = {
50
+ serverInfo: { name: 'my-app-mcp', version: '1.0.0' },
51
+ tools,
52
+ async authenticate(authHeader) {
53
+ const tenantId = await verifyBearer(authHeader); // throw McpError(...) to reject
54
+ return { allowedTools: null, principal: { tenantId } };
55
+ },
56
+ createContext: (principal) => principal,
57
+ // optional:
58
+ async rateLimit(principal) {
59
+ /* throw new McpError('rate limited', { statusCode: 429, data: { retryAfterSec: 30 } }) */
60
+ },
61
+ wrapToolCall: (info, run) => withAudit(info, run),
62
+ };
63
+
64
+ // 3. Dispatch a request from your HTTP route.
65
+ const { statusCode, response } = await handleMcpRequest(config, {
66
+ authHeader: req.headers.authorization ?? null,
67
+ body: req.body,
68
+ });
69
+ ```
70
+
71
+ ## Hook contract
72
+
73
+ | Hook | Required | Purpose |
74
+ | --------------- | -------- | ----------------------------------------------------------------------- |
75
+ | `authenticate` | yes | Resolve + authorize the caller; returns `{ allowedTools, principal }`. |
76
+ | `createContext` | yes | Build the value passed to each tool's `run` (may be async). |
77
+ | `rateLimit` | no | Pre-dispatch throttle. Throw to reject. |
78
+ | `wrapToolCall` | no | Wrap each invocation (audit-log bracket, tracing span, etc.). |
79
+
80
+ Errors thrown from `authenticate` / `rateLimit` are mapped to the JSON-RPC error
81
+ response. They may be an `McpError` (carrying `statusCode` / `rpcCode` / `data`)
82
+ or any error exposing those fields — a host's existing error classes work
83
+ unchanged. A `retryAfterSec` field is lifted into `error.data` automatically.
84
+
85
+ A tool's own thrown error is **not** a protocol error: per the MCP spec it is
86
+ returned as a successful response with `isError: true`, so the agent can read the
87
+ message and recover.
88
+
89
+ ## Allow-lists
90
+
91
+ `authenticate` returns `allowedTools`: `null` exposes every registered tool;
92
+ a populated `ReadonlySet<string>` restricts both `tools/list` and `tools/call`
93
+ to those names (handy for scoping a per-token capability set).
94
+
95
+ ## Bearer tokens & storage
96
+
97
+ MCP servers authenticate agents with long-lived bearer tokens. This package
98
+ ships the whole generic stack so you don't re-build it per app:
99
+
100
+ - **Format & primitives** (no deps, `node:crypto`): `generateBearerToken`,
101
+ `parseScopedToken`, `parseBearer`, `bearerTokenPrefix`. Tokens are
102
+ `vk_<scope>_<secret>`, where `scope` is an opaque owner key the verifier can
103
+ read _before_ hashing to narrow a lookup.
104
+ - **Postgres store** (`Querier`-first, scrypt-hashed): `createMcpToken`,
105
+ `listMcpTokens`, `revokeMcpToken`, `verifyMcpToken`. Only a scrypt hash + the
106
+ lookup `prefix` are persisted; the plaintext is returned once from
107
+ `createMcpToken` and is unrecoverable after.
108
+ - **Migration**: `mcp_tokens` ships as `migrations/vk_mcp_0001_tokens.sql` and is
109
+ **auto-discovered by `vk migrate`** for any app that depends on this package
110
+ (via the `vk.migrations` field) — no wiring required. `getMcpMigrationsDir()`
111
+ is the explicit escape hatch for `vk.config.ts:extraMigrationsDirs`.
112
+
113
+ The store is keyed on a generic `scope` (text, no foreign key), so it is not
114
+ coupled to any host's tenancy model. A host maps `scope` to whatever it owns — a
115
+ tenant slug, a user id, a project id — and layers its own checks on top:
116
+
117
+ ```ts
118
+ import { query } from '@venturekit/data';
119
+ import { createMcpToken, verifyMcpToken } from '@venturekit/mcp';
120
+
121
+ // Issue (scope = the host's owner key — here, a tenant slug):
122
+ const { row, token } = await createMcpToken(query, {
123
+ scope: tenant.slug,
124
+ label: 'Cascade workflow',
125
+ allowedTools: ['add_blog_post'], // omit/empty → every tool
126
+ createdBy: user.id,
127
+ });
128
+ // `token` is the plaintext — surface it exactly once.
129
+
130
+ // Verify inside your `authenticate` hook:
131
+ const tok = await verifyMcpToken(query, plaintext); // active row, or null
132
+ if (!tok) throw new McpError('Invalid token', { statusCode: 401 });
133
+ // …then resolve `tok.scope` to your domain object + enforce its status.
134
+ ```
135
+
136
+ Pass any `@venturekit/data`-compatible `query`; the store never imports a DB
137
+ driver itself.
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Error type for MCP hooks.
3
+ *
4
+ * Hosts can throw {@link McpError} from `authenticate` / `rateLimit` to
5
+ * control the HTTP status, the JSON-RPC error code, and any structured
6
+ * `data` payload returned to the client. The dispatcher also duck-types
7
+ * arbitrary thrown errors (reading `statusCode` / `rpcCode` / `data` /
8
+ * `retryAfterSec` when present), so a host's existing error classes work
9
+ * without extending this one.
10
+ */
11
+ export interface McpErrorOptions {
12
+ /** HTTP status code the transport should respond with. */
13
+ statusCode?: number;
14
+ /** JSON-RPC error code (`error.code`). */
15
+ rpcCode?: number;
16
+ /** Structured payload surfaced as `error.data`. */
17
+ data?: unknown;
18
+ }
19
+ export declare class McpError extends Error {
20
+ readonly statusCode?: number;
21
+ readonly rpcCode?: number;
22
+ readonly data?: unknown;
23
+ constructor(message: string, options?: McpErrorOptions);
24
+ }
25
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,WAAW,eAAe;IAC9B,0DAA0D;IAC1D,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,0CAA0C;IAC1C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mDAAmD;IACnD,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED,qBAAa,QAAS,SAAQ,KAAK;IACjC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;gBAEZ,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,eAAoB;CAW3D"}
package/dist/errors.js ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Error type for MCP hooks.
3
+ *
4
+ * Hosts can throw {@link McpError} from `authenticate` / `rateLimit` to
5
+ * control the HTTP status, the JSON-RPC error code, and any structured
6
+ * `data` payload returned to the client. The dispatcher also duck-types
7
+ * arbitrary thrown errors (reading `statusCode` / `rpcCode` / `data` /
8
+ * `retryAfterSec` when present), so a host's existing error classes work
9
+ * without extending this one.
10
+ */
11
+ export class McpError extends Error {
12
+ statusCode;
13
+ rpcCode;
14
+ data;
15
+ constructor(message, options = {}) {
16
+ super(message);
17
+ this.name = 'McpError';
18
+ // Only carry what the caller explicitly set. Leaving these undefined
19
+ // lets the dispatcher's `mapError` apply the context-appropriate
20
+ // fallback (e.g. -32001 for an auth-phase throw, -32029 for a
21
+ // rate-limit throw) instead of a generic -32603 swallowing it.
22
+ if (options.statusCode !== undefined)
23
+ this.statusCode = options.statusCode;
24
+ if (options.rpcCode !== undefined)
25
+ this.rpcCode = options.rpcCode;
26
+ if (options.data !== undefined)
27
+ this.data = options.data;
28
+ }
29
+ }
30
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAWH,MAAM,OAAO,QAAS,SAAQ,KAAK;IACxB,UAAU,CAAU;IACpB,OAAO,CAAU;IACjB,IAAI,CAAW;IAExB,YAAY,OAAe,EAAE,UAA2B,EAAE;QACxD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;QACvB,qEAAqE;QACrE,iEAAiE;QACjE,8DAA8D;QAC9D,+DAA+D;QAC/D,IAAI,OAAO,CAAC,UAAU,KAAK,SAAS;YAAE,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;QAC3E,IAAI,OAAO,CAAC,OAAO,KAAK,SAAS;YAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAClE,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS;YAAE,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAC3D,CAAC;CACF"}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @venturekit/mcp
3
+ *
4
+ * Transport-agnostic Model Context Protocol (MCP) server primitives:
5
+ * a stateless JSON-RPC dispatcher, a typed tool registry, and a
6
+ * Zod -> JSON-Schema serializer for `tools/list`.
7
+ *
8
+ * The package owns only the protocol. Authentication, rate limiting,
9
+ * audit logging, and per-call context assembly are injected as hooks
10
+ * (see {@link McpServerConfig}), so any VentureKit app can stand up an
11
+ * MCP endpoint by supplying a tool registry plus those hooks.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { handleMcpRequest, type McpServerConfig } from '@venturekit/mcp';
16
+ *
17
+ * const config: McpServerConfig<MyCtx, MyPrincipal> = {
18
+ * serverInfo: { name: 'my-app-mcp', version: '1.0.0' },
19
+ * tools: ALL_TOOLS,
20
+ * authenticate: (header) => verifyToken(header),
21
+ * createContext: (principal, toolName) => buildCtx(principal, toolName),
22
+ * };
23
+ *
24
+ * const out = await handleMcpRequest(config, { authHeader, body });
25
+ * ```
26
+ */
27
+ export { handleMcpRequest } from './server.js';
28
+ export { zodToJsonSchema, type JsonSchema } from './json-schema.js';
29
+ export { McpError, type McpErrorOptions } from './errors.js';
30
+ export { generateBearerToken, bearerTokenPrefix, parseScopedToken, parseBearer, DEFAULT_PREFIX_LENGTH, type GenerateBearerTokenOptions, type GeneratedBearerToken, type ParsedScopedToken, } from './tokens.js';
31
+ export { createMcpToken, listMcpTokens, revokeMcpToken, verifyMcpToken, hashTokenSecret, verifyTokenSecret, type Querier, type McpTokenRow, type CreateMcpTokenInput, type CreatedMcpToken, } from './store.js';
32
+ export { getMcpMigrationsDir } from './path.js';
33
+ export type { JsonRpcError, JsonRpcRequest, JsonRpcResponse, McpAuthResult, McpHandlerInput, McpHandlerOutput, McpServerConfig, McpServerInfo, McpTool, McpToolCallInfo, McpToolRegistry, } from './types.js';
34
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,KAAK,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACpE,OAAO,EAAE,QAAQ,EAAE,KAAK,eAAe,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,gBAAgB,EAChB,WAAW,EACX,qBAAqB,EACrB,KAAK,0BAA0B,EAC/B,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,GACvB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,cAAc,EACd,aAAa,EACb,cAAc,EACd,cAAc,EACd,eAAe,EACf,iBAAiB,EACjB,KAAK,OAAO,EACZ,KAAK,WAAW,EAChB,KAAK,mBAAmB,EACxB,KAAK,eAAe,GACrB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAChD,YAAY,EACV,YAAY,EACZ,cAAc,EACd,eAAe,EACf,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,aAAa,EACb,OAAO,EACP,eAAe,EACf,eAAe,GAChB,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @venturekit/mcp
3
+ *
4
+ * Transport-agnostic Model Context Protocol (MCP) server primitives:
5
+ * a stateless JSON-RPC dispatcher, a typed tool registry, and a
6
+ * Zod -> JSON-Schema serializer for `tools/list`.
7
+ *
8
+ * The package owns only the protocol. Authentication, rate limiting,
9
+ * audit logging, and per-call context assembly are injected as hooks
10
+ * (see {@link McpServerConfig}), so any VentureKit app can stand up an
11
+ * MCP endpoint by supplying a tool registry plus those hooks.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { handleMcpRequest, type McpServerConfig } from '@venturekit/mcp';
16
+ *
17
+ * const config: McpServerConfig<MyCtx, MyPrincipal> = {
18
+ * serverInfo: { name: 'my-app-mcp', version: '1.0.0' },
19
+ * tools: ALL_TOOLS,
20
+ * authenticate: (header) => verifyToken(header),
21
+ * createContext: (principal, toolName) => buildCtx(principal, toolName),
22
+ * };
23
+ *
24
+ * const out = await handleMcpRequest(config, { authHeader, body });
25
+ * ```
26
+ */
27
+ export { handleMcpRequest } from './server.js';
28
+ export { zodToJsonSchema } from './json-schema.js';
29
+ export { McpError } from './errors.js';
30
+ export { generateBearerToken, bearerTokenPrefix, parseScopedToken, parseBearer, DEFAULT_PREFIX_LENGTH, } from './tokens.js';
31
+ export { createMcpToken, listMcpTokens, revokeMcpToken, verifyMcpToken, hashTokenSecret, verifyTokenSecret, } from './store.js';
32
+ export { getMcpMigrationsDir } from './path.js';
33
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAmB,MAAM,kBAAkB,CAAC;AACpE,OAAO,EAAE,QAAQ,EAAwB,MAAM,aAAa,CAAC;AAC7D,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,gBAAgB,EAChB,WAAW,EACX,qBAAqB,GAItB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,cAAc,EACd,aAAa,EACb,cAAc,EACd,cAAc,EACd,eAAe,EACf,iBAAiB,GAKlB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Minimal Zod -> JSON-Schema serializer for MCP `tools/list` output.
3
+ *
4
+ * Implements the subset MCP tool inputs realistically use: `z.object`
5
+ * with primitives, `optional`, `nullable`, `default`, `enum`, native
6
+ * enum, `array`, `record`, `union`, `literal`, plus the wrappers Zod
7
+ * inserts for `.refine()` / `.superRefine()` / `.transform()`
8
+ * (`ZodEffects`), `.pipe()` (`ZodPipeline`) and `.readonly()`
9
+ * (`ZodReadonly`) — these are unwrapped to the schema they decorate so
10
+ * a refined object still advertises its real properties.
11
+ *
12
+ * `zod` is imported type-only; this function reads `._def` structurally
13
+ * and never constructs a schema, so the package carries no runtime zod
14
+ * dependency.
15
+ */
16
+ import type { ZodTypeAny } from 'zod';
17
+ export interface JsonSchema {
18
+ type?: string | string[];
19
+ description?: string;
20
+ properties?: Record<string, JsonSchema>;
21
+ required?: string[];
22
+ items?: JsonSchema;
23
+ enum?: unknown[];
24
+ default?: unknown;
25
+ oneOf?: JsonSchema[];
26
+ additionalProperties?: JsonSchema | boolean;
27
+ format?: string;
28
+ minLength?: number;
29
+ maxLength?: number;
30
+ minimum?: number;
31
+ maximum?: number;
32
+ pattern?: string;
33
+ }
34
+ export declare function zodToJsonSchema(schema: ZodTypeAny): JsonSchema;
35
+ //# sourceMappingURL=json-schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json-schema.d.ts","sourceRoot":"","sources":["../src/json-schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EASV,UAAU,EAEX,MAAM,KAAK,CAAC;AAEb,MAAM,WAAW,UAAU;IACzB,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IACzB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACxC,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB,IAAI,CAAC,EAAE,OAAO,EAAE,CAAC;IACjB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,UAAU,EAAE,CAAC;IACrB,oBAAoB,CAAC,EAAE,UAAU,GAAG,OAAO,CAAC;IAC5C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,UAAU,GAAG,UAAU,CAgG9D"}
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Minimal Zod -> JSON-Schema serializer for MCP `tools/list` output.
3
+ *
4
+ * Implements the subset MCP tool inputs realistically use: `z.object`
5
+ * with primitives, `optional`, `nullable`, `default`, `enum`, native
6
+ * enum, `array`, `record`, `union`, `literal`, plus the wrappers Zod
7
+ * inserts for `.refine()` / `.superRefine()` / `.transform()`
8
+ * (`ZodEffects`), `.pipe()` (`ZodPipeline`) and `.readonly()`
9
+ * (`ZodReadonly`) — these are unwrapped to the schema they decorate so
10
+ * a refined object still advertises its real properties.
11
+ *
12
+ * `zod` is imported type-only; this function reads `._def` structurally
13
+ * and never constructs a schema, so the package carries no runtime zod
14
+ * dependency.
15
+ */
16
+ export function zodToJsonSchema(schema) {
17
+ const def = schema._def;
18
+ const t = def.typeName;
19
+ switch (t) {
20
+ case 'ZodObject': {
21
+ const shape = schema.shape;
22
+ const properties = {};
23
+ const required = [];
24
+ for (const [k, v] of Object.entries(shape)) {
25
+ properties[k] = zodToJsonSchema(v);
26
+ if (!isOptional(v))
27
+ required.push(k);
28
+ }
29
+ return {
30
+ type: 'object',
31
+ properties,
32
+ ...(required.length ? { required } : {}),
33
+ additionalProperties: false,
34
+ };
35
+ }
36
+ case 'ZodString': {
37
+ const out = { type: 'string' };
38
+ const checks = (schema._def.checks ?? []);
39
+ for (const c of checks) {
40
+ if (c.kind === 'min' && typeof c.value === 'number')
41
+ out.minLength = c.value;
42
+ if (c.kind === 'max' && typeof c.value === 'number')
43
+ out.maxLength = c.value;
44
+ if (c.kind === 'uuid')
45
+ out.format = 'uuid';
46
+ if (c.kind === 'email')
47
+ out.format = 'email';
48
+ if (c.kind === 'url')
49
+ out.format = 'uri';
50
+ if (c.kind === 'datetime')
51
+ out.format = 'date-time';
52
+ if (c.kind === 'regex' && c.regex)
53
+ out.pattern = c.regex.source;
54
+ }
55
+ return out;
56
+ }
57
+ case 'ZodNumber': {
58
+ const out = { type: 'number' };
59
+ const checks = (schema._def
60
+ .checks ?? []);
61
+ for (const c of checks) {
62
+ if (c.kind === 'min' && typeof c.value === 'number')
63
+ out.minimum = c.value;
64
+ if (c.kind === 'max' && typeof c.value === 'number')
65
+ out.maximum = c.value;
66
+ if (c.kind === 'int')
67
+ out.type = 'integer';
68
+ }
69
+ return out;
70
+ }
71
+ case 'ZodBoolean':
72
+ return { type: 'boolean' };
73
+ case 'ZodEnum':
74
+ return { type: 'string', enum: schema.options };
75
+ case 'ZodNativeEnum':
76
+ return { type: 'string', enum: Object.values(schema.enum) };
77
+ case 'ZodArray': {
78
+ const inner = schema._def.type;
79
+ return { type: 'array', items: zodToJsonSchema(inner) };
80
+ }
81
+ case 'ZodRecord': {
82
+ const valueSchema = schema._def.valueType;
83
+ return { type: 'object', additionalProperties: zodToJsonSchema(valueSchema) };
84
+ }
85
+ case 'ZodOptional':
86
+ case 'ZodNullable':
87
+ case 'ZodDefault': {
88
+ const inner = schema._def.innerType;
89
+ const out = zodToJsonSchema(inner);
90
+ if (t === 'ZodDefault') {
91
+ const defGetter = schema._def.defaultValue;
92
+ if (typeof defGetter === 'function')
93
+ out.default = defGetter();
94
+ }
95
+ return out;
96
+ }
97
+ case 'ZodEffects':
98
+ // `.refine()` / `.superRefine()` / `.transform()` / `z.preprocess`
99
+ return zodToJsonSchema(schema._def.schema);
100
+ case 'ZodPipeline':
101
+ // `a.pipe(b)` — describe the output side.
102
+ return zodToJsonSchema(schema._def.out);
103
+ case 'ZodReadonly':
104
+ return zodToJsonSchema(schema._def.innerType);
105
+ case 'ZodUnion': {
106
+ const opts = schema._def.options;
107
+ return { oneOf: opts.map((o) => zodToJsonSchema(o)) };
108
+ }
109
+ case 'ZodLiteral': {
110
+ const v = schema._def.value;
111
+ return { type: typeof v === 'number' ? 'number' : 'string', enum: [v] };
112
+ }
113
+ case 'ZodAny':
114
+ case 'ZodUnknown':
115
+ return {};
116
+ default:
117
+ return {};
118
+ }
119
+ }
120
+ function isOptional(schema) {
121
+ const def = schema._def;
122
+ if (def.typeName === 'ZodOptional' || def.typeName === 'ZodDefault')
123
+ return true;
124
+ if (def.typeName === 'ZodNullable')
125
+ return false; // nullable but still required
126
+ // Unwrap refinement / pipeline / readonly wrappers so an optional
127
+ // field that's been `.refine()`d still reads as optional.
128
+ if ((def.typeName === 'ZodEffects' || def.typeName === 'ZodReadonly') &&
129
+ def.innerType) {
130
+ return isOptional(def.innerType);
131
+ }
132
+ if (def.typeName === 'ZodEffects') {
133
+ const inner = schema._def.schema;
134
+ if (inner)
135
+ return isOptional(inner);
136
+ }
137
+ return false;
138
+ }
139
+ //# sourceMappingURL=json-schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json-schema.js","sourceRoot":"","sources":["../src/json-schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAiCH,MAAM,UAAU,eAAe,CAAC,MAAkB;IAChD,MAAM,GAAG,GAAG,MAAM,CAAC,IAA6B,CAAC;IACjD,MAAM,CAAC,GAAG,GAAG,CAAC,QAAQ,CAAC;IAEvB,QAAQ,CAAC,EAAE,CAAC;QACV,KAAK,WAAW,CAAC,CAAC,CAAC;YACjB,MAAM,KAAK,GAAI,MAAiC,CAAC,KAAK,CAAC;YACvD,MAAM,UAAU,GAA+B,EAAE,CAAC;YAClD,MAAM,QAAQ,GAAa,EAAE,CAAC;YAC9B,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;gBAC3C,UAAU,CAAC,CAAC,CAAC,GAAG,eAAe,CAAC,CAAe,CAAC,CAAC;gBACjD,IAAI,CAAC,UAAU,CAAC,CAAe,CAAC;oBAAE,QAAQ,C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