@vllnt/convex-helpers 0.1.0-canary.1e0f54a
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 +21 -0
- package/README.md +125 -0
- package/dist/index.d.ts +41 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +53 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/auth.d.ts +11 -0
- package/dist/mcp/auth.d.ts.map +1 -0
- package/dist/mcp/auth.js +36 -0
- package/dist/mcp/auth.js.map +1 -0
- package/dist/mcp/index.d.ts +7 -0
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +5 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/pagination/context.d.ts +9 -0
- package/dist/mcp/pagination/context.d.ts.map +1 -0
- package/dist/mcp/pagination/context.js +21 -0
- package/dist/mcp/pagination/context.js.map +1 -0
- package/dist/mcp/pagination/cursor.d.ts +7 -0
- package/dist/mcp/pagination/cursor.d.ts.map +1 -0
- package/dist/mcp/pagination/cursor.js +60 -0
- package/dist/mcp/pagination/cursor.js.map +1 -0
- package/dist/mcp/pagination/handlers.d.ts +12 -0
- package/dist/mcp/pagination/handlers.d.ts.map +1 -0
- package/dist/mcp/pagination/handlers.js +91 -0
- package/dist/mcp/pagination/handlers.js.map +1 -0
- package/dist/mcp/pagination/types.d.ts +26 -0
- package/dist/mcp/pagination/types.d.ts.map +1 -0
- package/dist/mcp/pagination/types.js +2 -0
- package/dist/mcp/pagination/types.js.map +1 -0
- package/dist/mcp/resources/helpers.d.ts +9 -0
- package/dist/mcp/resources/helpers.d.ts.map +1 -0
- package/dist/mcp/resources/helpers.js +8 -0
- package/dist/mcp/resources/helpers.js.map +1 -0
- package/dist/mcp/resources/register.d.ts +14 -0
- package/dist/mcp/resources/register.d.ts.map +1 -0
- package/dist/mcp/resources/register.js +40 -0
- package/dist/mcp/resources/register.js.map +1 -0
- package/dist/mcp/resources/types.d.ts +7 -0
- package/dist/mcp/resources/types.d.ts.map +1 -0
- package/dist/mcp/resources/types.js +2 -0
- package/dist/mcp/resources/types.js.map +1 -0
- package/dist/mcp/server.d.ts +3 -0
- package/dist/mcp/server.d.ts.map +1 -0
- package/dist/mcp/server.js +139 -0
- package/dist/mcp/server.js.map +1 -0
- package/dist/mcp/tools/helpers.d.ts +16 -0
- package/dist/mcp/tools/helpers.d.ts.map +1 -0
- package/dist/mcp/tools/helpers.js +34 -0
- package/dist/mcp/tools/helpers.js.map +1 -0
- package/dist/mcp/tools/register.d.ts +23 -0
- package/dist/mcp/tools/register.d.ts.map +1 -0
- package/dist/mcp/tools/register.js +195 -0
- package/dist/mcp/tools/register.js.map +1 -0
- package/dist/mcp/tools/types.d.ts +71 -0
- package/dist/mcp/tools/types.d.ts.map +1 -0
- package/dist/mcp/tools/types.js +2 -0
- package/dist/mcp/tools/types.js.map +1 -0
- package/dist/mcp/types.d.ts +50 -0
- package/dist/mcp/types.d.ts.map +1 -0
- package/dist/mcp/types.js +2 -0
- package/dist/mcp/types.js.map +1 -0
- package/dist/mcp/validators.d.ts +8 -0
- package/dist/mcp/validators.d.ts.map +1 -0
- package/dist/mcp/validators.js +135 -0
- package/dist/mcp/validators.js.map +1 -0
- package/package.json +95 -0
- package/src/index.test.ts +164 -0
- package/src/index.ts +62 -0
- package/src/mcp/auth.ts +53 -0
- package/src/mcp/index.ts +23 -0
- package/src/mcp/pagination/context.ts +27 -0
- package/src/mcp/pagination/cursor.ts +99 -0
- package/src/mcp/pagination/handlers.ts +172 -0
- package/src/mcp/pagination/types.ts +27 -0
- package/src/mcp/resources/helpers.ts +19 -0
- package/src/mcp/resources/register.ts +63 -0
- package/src/mcp/resources/types.ts +7 -0
- package/src/mcp/server.ts +209 -0
- package/src/mcp/tools/helpers.ts +47 -0
- package/src/mcp/tools/register.ts +256 -0
- package/src/mcp/tools/types.ts +74 -0
- package/src/mcp/types.ts +65 -0
- package/src/mcp/validators.ts +175 -0
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
type CursorPayload = {
|
|
2
|
+
m: string;
|
|
3
|
+
o: number;
|
|
4
|
+
v: 1;
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
const SEPARATOR = ".";
|
|
8
|
+
|
|
9
|
+
function isCursorPayload(value: unknown): value is CursorPayload {
|
|
10
|
+
if (typeof value !== "object" || value === null) return false;
|
|
11
|
+
const object = value as Record<string, unknown>;
|
|
12
|
+
return (
|
|
13
|
+
typeof object.v === "number" &&
|
|
14
|
+
typeof object.m === "string" &&
|
|
15
|
+
typeof object.o === "number"
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function importKey(
|
|
20
|
+
secret: string,
|
|
21
|
+
usages: KeyUsage[],
|
|
22
|
+
): Promise<CryptoKey> {
|
|
23
|
+
return crypto.subtle.importKey(
|
|
24
|
+
"raw",
|
|
25
|
+
new TextEncoder().encode(secret),
|
|
26
|
+
{ hash: "SHA-256", name: "HMAC" },
|
|
27
|
+
false,
|
|
28
|
+
usages,
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function hmacSign(payload: string, secret: string): Promise<ArrayBuffer> {
|
|
33
|
+
const key = await importKey(secret, ["sign"]);
|
|
34
|
+
return crypto.subtle.sign("HMAC", key, new TextEncoder().encode(payload));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function hmacVerify(
|
|
38
|
+
payload: string,
|
|
39
|
+
signature: string,
|
|
40
|
+
secret: string,
|
|
41
|
+
): Promise<boolean> {
|
|
42
|
+
let sigBytes: Uint8Array<ArrayBuffer>;
|
|
43
|
+
try {
|
|
44
|
+
sigBytes = new Uint8Array(
|
|
45
|
+
Array.from(atob(signature), (c) => c.charCodeAt(0)),
|
|
46
|
+
);
|
|
47
|
+
} catch {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
const key = await importKey(secret, ["verify"]);
|
|
51
|
+
return crypto.subtle.verify(
|
|
52
|
+
"HMAC",
|
|
53
|
+
key,
|
|
54
|
+
sigBytes,
|
|
55
|
+
new TextEncoder().encode(payload),
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function arrayBufferToBase64(buf: ArrayBuffer): string {
|
|
60
|
+
return btoa(
|
|
61
|
+
Array.from(new Uint8Array(buf), (b) => String.fromCharCode(b)).join(""),
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function encodeCursor(
|
|
66
|
+
method: string,
|
|
67
|
+
offset: number,
|
|
68
|
+
secret: string,
|
|
69
|
+
): Promise<string> {
|
|
70
|
+
const payload: CursorPayload = { m: method, o: offset, v: 1 };
|
|
71
|
+
const json = JSON.stringify(payload);
|
|
72
|
+
const b64 = btoa(json);
|
|
73
|
+
const sig = await hmacSign(b64, secret);
|
|
74
|
+
return `${b64}${SEPARATOR}${arrayBufferToBase64(sig)}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function decodeCursor(
|
|
78
|
+
cursor: string,
|
|
79
|
+
expectedMethod: string,
|
|
80
|
+
secret: string,
|
|
81
|
+
): Promise<{ error: string } | { offset: number }> {
|
|
82
|
+
const separatorIndex = cursor.lastIndexOf(SEPARATOR);
|
|
83
|
+
if (separatorIndex === -1) return { error: "invalid or expired cursor" };
|
|
84
|
+
|
|
85
|
+
const b64 = cursor.slice(0, separatorIndex);
|
|
86
|
+
const sig = cursor.slice(separatorIndex + 1);
|
|
87
|
+
|
|
88
|
+
const valid = await hmacVerify(b64, sig, secret);
|
|
89
|
+
if (!valid) return { error: "invalid or expired cursor" };
|
|
90
|
+
|
|
91
|
+
// Safe to parse without try-catch: HMAC verification above guarantees b64 is
|
|
92
|
+
// a payload we signed, so atob + JSON.parse will not throw.
|
|
93
|
+
const raw: unknown = JSON.parse(atob(b64));
|
|
94
|
+
if (!isCursorPayload(raw)) return { error: "invalid or expired cursor" };
|
|
95
|
+
if (raw.v !== 1) return { error: "invalid or expired cursor" };
|
|
96
|
+
if (raw.m !== expectedMethod) return { error: "invalid or expired cursor" };
|
|
97
|
+
if (raw.o < 0) return { error: "invalid or expired cursor" };
|
|
98
|
+
return { offset: raw.o };
|
|
99
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import {
|
|
3
|
+
ErrorCode,
|
|
4
|
+
ListToolsRequestSchema,
|
|
5
|
+
McpError,
|
|
6
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
|
|
9
|
+
import { decodeCursor, encodeCursor } from "./cursor.js";
|
|
10
|
+
import type { ToolPage } from "./types.js";
|
|
11
|
+
|
|
12
|
+
type McpTool = {
|
|
13
|
+
description?: string;
|
|
14
|
+
inputSchema: Record<string, unknown>;
|
|
15
|
+
name: string;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
type ToolListFn = () => Promise<McpTool[]>;
|
|
19
|
+
type OrigHandler = (
|
|
20
|
+
request: unknown,
|
|
21
|
+
extra: unknown,
|
|
22
|
+
) => Promise<{ tools: McpTool[] }>;
|
|
23
|
+
|
|
24
|
+
/* v8 ignore start -- canary: only triggers if SDK removes tools/list handler */
|
|
25
|
+
function assertHandler(handler: OrigHandler | undefined): OrigHandler {
|
|
26
|
+
if (!handler)
|
|
27
|
+
throw new Error(
|
|
28
|
+
"[convex-mcp] tools/list handler not found — SDK API may have changed.",
|
|
29
|
+
);
|
|
30
|
+
return handler;
|
|
31
|
+
}
|
|
32
|
+
/* v8 ignore stop */
|
|
33
|
+
|
|
34
|
+
export function getOriginalToolsList(mcpServer: McpServer): ToolListFn {
|
|
35
|
+
type HandlerMap = Map<string, OrigHandler>;
|
|
36
|
+
const handlers = (
|
|
37
|
+
mcpServer.server as unknown as { _requestHandlers: HandlerMap }
|
|
38
|
+
)._requestHandlers;
|
|
39
|
+
const origHandler = assertHandler(handlers.get("tools/list"));
|
|
40
|
+
|
|
41
|
+
return async (): Promise<McpTool[]> => {
|
|
42
|
+
const result = await origHandler(
|
|
43
|
+
{ method: "tools/list", params: {} },
|
|
44
|
+
{ signal: new AbortController().signal },
|
|
45
|
+
);
|
|
46
|
+
return result.tools;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function paginateTools<T extends object>(
|
|
51
|
+
tools: T[],
|
|
52
|
+
method: string,
|
|
53
|
+
pageSize: number,
|
|
54
|
+
cursor: string,
|
|
55
|
+
secret: string,
|
|
56
|
+
): Promise<ToolPage<T> | { error: string }> {
|
|
57
|
+
let offset = 0;
|
|
58
|
+
|
|
59
|
+
if (cursor !== "") {
|
|
60
|
+
const decoded = await decodeCursor(cursor, method, secret);
|
|
61
|
+
if ("error" in decoded) return { error: decoded.error };
|
|
62
|
+
offset = decoded.offset;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/* v8 ignore start -- unreachable from public API: HMAC prevents crafting out-of-bounds cursors */
|
|
66
|
+
if (offset >= tools.length && tools.length > 0)
|
|
67
|
+
return { error: "invalid or expired cursor" };
|
|
68
|
+
/* v8 ignore stop */
|
|
69
|
+
|
|
70
|
+
const page = tools.slice(offset, offset + pageSize);
|
|
71
|
+
const hasMore = offset + pageSize < tools.length;
|
|
72
|
+
const nextCursor = hasMore
|
|
73
|
+
? await encodeCursor(method, offset + pageSize, secret)
|
|
74
|
+
: undefined;
|
|
75
|
+
|
|
76
|
+
return { nextCursor, tools: page };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function registerPaginationHandlers(
|
|
80
|
+
mcpServer: McpServer,
|
|
81
|
+
getAllTools: ToolListFn,
|
|
82
|
+
pageSize: number,
|
|
83
|
+
secret: string,
|
|
84
|
+
): void {
|
|
85
|
+
mcpServer.server.setRequestHandler(
|
|
86
|
+
ListToolsRequestSchema,
|
|
87
|
+
async (request) => {
|
|
88
|
+
const cursor = request.params?.cursor;
|
|
89
|
+
const allTools = await getAllTools();
|
|
90
|
+
|
|
91
|
+
if (cursor === undefined) {
|
|
92
|
+
return { tools: allTools };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const result = await paginateTools(
|
|
96
|
+
allTools,
|
|
97
|
+
"tools/list",
|
|
98
|
+
pageSize,
|
|
99
|
+
cursor,
|
|
100
|
+
secret,
|
|
101
|
+
);
|
|
102
|
+
if ("error" in result) {
|
|
103
|
+
throw new McpError(ErrorCode.InvalidParams, result.error);
|
|
104
|
+
}
|
|
105
|
+
return { nextCursor: result.nextCursor, tools: result.tools };
|
|
106
|
+
},
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function registerTwoPhaseHandlers(
|
|
111
|
+
mcpServer: McpServer,
|
|
112
|
+
getAllTools: ToolListFn,
|
|
113
|
+
pageSize: number,
|
|
114
|
+
secret: string,
|
|
115
|
+
): void {
|
|
116
|
+
const listSummarySchema = z.object({
|
|
117
|
+
method: z.literal("tools/list_summary"),
|
|
118
|
+
params: z.object({ cursor: z.string().optional() }).optional(),
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
mcpServer.server.setRequestHandler(listSummarySchema, async (request) => {
|
|
122
|
+
const allTools = await getAllTools();
|
|
123
|
+
const summaries = allTools.map((t) => ({
|
|
124
|
+
/* v8 ignore next -- both branches tested; v8 misreports ternary in .map() */
|
|
125
|
+
description: t.description === undefined ? "" : t.description,
|
|
126
|
+
name: t.name,
|
|
127
|
+
}));
|
|
128
|
+
|
|
129
|
+
const cursor = request.params?.cursor;
|
|
130
|
+
if (cursor === undefined) {
|
|
131
|
+
return { tools: summaries };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const result = await paginateTools(
|
|
135
|
+
summaries,
|
|
136
|
+
"tools/list_summary",
|
|
137
|
+
pageSize,
|
|
138
|
+
cursor,
|
|
139
|
+
secret,
|
|
140
|
+
);
|
|
141
|
+
if ("error" in result) {
|
|
142
|
+
throw new McpError(ErrorCode.InvalidParams, result.error);
|
|
143
|
+
}
|
|
144
|
+
return { nextCursor: result.nextCursor, tools: result.tools };
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
const describeSchema = z.object({
|
|
148
|
+
method: z.literal("tools/describe"),
|
|
149
|
+
params: z.object({ name: z.string().optional() }).optional(),
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
mcpServer.server.setRequestHandler(describeSchema, async (request) => {
|
|
153
|
+
const name = request.params?.name;
|
|
154
|
+
if (!name) {
|
|
155
|
+
throw new McpError(
|
|
156
|
+
ErrorCode.InvalidParams,
|
|
157
|
+
"Invalid params: 'name' is required",
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const allTools = await getAllTools();
|
|
162
|
+
const tool = allTools.find((t) => t.name === name);
|
|
163
|
+
if (!tool) {
|
|
164
|
+
throw new McpError(
|
|
165
|
+
ErrorCode.InvalidParams,
|
|
166
|
+
`Invalid params: tool '${name}' not found`,
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return { tool };
|
|
171
|
+
});
|
|
172
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opt-in pagination for `tools/list` and two-phase tool discovery.
|
|
3
|
+
*
|
|
4
|
+
* `pageSize` is required for all pagination features including `twoPhaseDiscovery`.
|
|
5
|
+
* Must be >= 1. When enabled, `tools/list` without a cursor still returns ALL tools
|
|
6
|
+
* (backwards-compatible). Cursor pagination activates only when the client sends a cursor.
|
|
7
|
+
*
|
|
8
|
+
* `twoPhaseDiscovery` enables non-standard custom MCP methods (`tools/list_summary`,
|
|
9
|
+
* `tools/describe`). These are NOT part of the MCP spec — only custom agents that
|
|
10
|
+
* explicitly call these methods will benefit.
|
|
11
|
+
*/
|
|
12
|
+
export type PaginationConfig = {
|
|
13
|
+
/** Number of tools per page when client sends a cursor. Must be >= 1. */
|
|
14
|
+
pageSize: number;
|
|
15
|
+
/** Enable `tools/list_summary` + `tools/describe` custom methods. Default: false. */
|
|
16
|
+
twoPhaseDiscovery?: boolean;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export type ToolSummary = {
|
|
20
|
+
description: string;
|
|
21
|
+
name: string;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type ToolPage<T extends object> = {
|
|
25
|
+
nextCursor?: string;
|
|
26
|
+
tools: T[];
|
|
27
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ConvexValidator } from "../types.js";
|
|
2
|
+
|
|
3
|
+
import type { ResourceDef } from "./types.js";
|
|
4
|
+
|
|
5
|
+
type ResourceOptions = {
|
|
6
|
+
args?: ConvexValidator;
|
|
7
|
+
description?: string;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export function resource(
|
|
11
|
+
ref: unknown,
|
|
12
|
+
options: ResourceOptions = {},
|
|
13
|
+
): ResourceDef {
|
|
14
|
+
return {
|
|
15
|
+
args: options.args,
|
|
16
|
+
description: options.description,
|
|
17
|
+
ref,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
|
|
4
|
+
import type { ConvexClient } from "../types.js";
|
|
5
|
+
|
|
6
|
+
import type { ResourceDef } from "./types.js";
|
|
7
|
+
|
|
8
|
+
type PreparedResource = {
|
|
9
|
+
description: string | undefined;
|
|
10
|
+
resourceDef: ResourceDef;
|
|
11
|
+
template: ResourceTemplate;
|
|
12
|
+
uriPattern: string;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export function prepareResources(
|
|
16
|
+
resources: Record<string, ResourceDef>,
|
|
17
|
+
): PreparedResource[] {
|
|
18
|
+
return Object.entries(resources).map(([uriPattern, resourceDef]) => ({
|
|
19
|
+
description: resourceDef.description,
|
|
20
|
+
resourceDef,
|
|
21
|
+
template: new ResourceTemplate(uriPattern, { list: undefined }),
|
|
22
|
+
uriPattern,
|
|
23
|
+
}));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function registerResources(
|
|
27
|
+
mcpServer: McpServer,
|
|
28
|
+
client: ConvexClient,
|
|
29
|
+
resources: PreparedResource[],
|
|
30
|
+
): void {
|
|
31
|
+
for (const { description, resourceDef, template, uriPattern } of resources) {
|
|
32
|
+
mcpServer.resource(
|
|
33
|
+
uriPattern,
|
|
34
|
+
template,
|
|
35
|
+
{
|
|
36
|
+
description,
|
|
37
|
+
mimeType: "application/json",
|
|
38
|
+
},
|
|
39
|
+
async (uri, parameters: Record<string, unknown>) => {
|
|
40
|
+
try {
|
|
41
|
+
const result = await client.query(resourceDef.ref, parameters);
|
|
42
|
+
return {
|
|
43
|
+
contents: [
|
|
44
|
+
{
|
|
45
|
+
mimeType: "application/json",
|
|
46
|
+
text: JSON.stringify(result ?? null, null, 2),
|
|
47
|
+
uri: uri.href,
|
|
48
|
+
},
|
|
49
|
+
],
|
|
50
|
+
};
|
|
51
|
+
} catch (error) {
|
|
52
|
+
console.error("[convex-mcp] resource read failed", {
|
|
53
|
+
error,
|
|
54
|
+
resource: uriPattern,
|
|
55
|
+
});
|
|
56
|
+
// Mask the raw Convex error from the client (parity with the tool
|
|
57
|
+
// handler); the real error is logged server-side above.
|
|
58
|
+
throw new Error("Resource read failed");
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
3
|
+
import { ConvexHttpClient } from "convex/browser";
|
|
4
|
+
|
|
5
|
+
import { validateRequest } from "./auth.js";
|
|
6
|
+
import { createPaginationContext } from "./pagination/context.js";
|
|
7
|
+
import {
|
|
8
|
+
getOriginalToolsList,
|
|
9
|
+
registerPaginationHandlers,
|
|
10
|
+
registerTwoPhaseHandlers,
|
|
11
|
+
} from "./pagination/handlers.js";
|
|
12
|
+
import { prepareResources, registerResources } from "./resources/register.js";
|
|
13
|
+
import {
|
|
14
|
+
findToolsWithReservedArgs as findToolsWithReservedArguments,
|
|
15
|
+
prepareTools,
|
|
16
|
+
registerTools,
|
|
17
|
+
} from "./tools/register.js";
|
|
18
|
+
import type { ConvexClient, ConvexMCPServer, ServerConfig } from "./types.js";
|
|
19
|
+
|
|
20
|
+
function createDefaultClient(
|
|
21
|
+
convexUrl: string,
|
|
22
|
+
convexToken?: string,
|
|
23
|
+
): ConvexClient {
|
|
24
|
+
const client = new ConvexHttpClient(convexUrl);
|
|
25
|
+
if (convexToken) {
|
|
26
|
+
client.setAuth(convexToken);
|
|
27
|
+
}
|
|
28
|
+
return client;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function addRequestId(response: Response, requestId: string): Response {
|
|
32
|
+
const headers = new Headers(response.headers);
|
|
33
|
+
headers.set("X-Request-Id", requestId);
|
|
34
|
+
return new Response(response.body, {
|
|
35
|
+
headers,
|
|
36
|
+
status: response.status,
|
|
37
|
+
statusText: response.statusText,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function createMCPServer(config: ServerConfig): ConvexMCPServer {
|
|
42
|
+
if (!config.auth?.validate) {
|
|
43
|
+
throw new Error(
|
|
44
|
+
"Auth is required. Provide auth.validate to createMCPServer(). " +
|
|
45
|
+
"This package enforces default-deny — no open MCP endpoints.",
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const injectedClient = config.client;
|
|
50
|
+
|
|
51
|
+
if (injectedClient && config.auth.convexToken) {
|
|
52
|
+
throw new Error(
|
|
53
|
+
"Cannot use both 'client' and 'auth.convexToken'. When providing a custom client, " +
|
|
54
|
+
"handle auth token propagation in your client implementation directly.",
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let resolvedConvexUrl: string | undefined;
|
|
59
|
+
if (!injectedClient) {
|
|
60
|
+
resolvedConvexUrl =
|
|
61
|
+
config.convexUrl ??
|
|
62
|
+
process.env.CONVEX_URL ??
|
|
63
|
+
process.env.NEXT_PUBLIC_CONVEX_URL;
|
|
64
|
+
if (!resolvedConvexUrl) {
|
|
65
|
+
throw new Error(
|
|
66
|
+
"Convex URL not found. Set CONVEX_URL or NEXT_PUBLIC_CONVEX_URL environment variable, " +
|
|
67
|
+
"or pass convexUrl or client to createMCPServer().",
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const serverName = config.name ?? "convex-mcp";
|
|
73
|
+
const serverVersion = config.version ?? "0.1.0";
|
|
74
|
+
const hooks = config.hooks;
|
|
75
|
+
|
|
76
|
+
const prepared = prepareTools(config.tools ?? {});
|
|
77
|
+
const preparedRes = prepareResources(config.resources ?? {});
|
|
78
|
+
const paginationCtx = createPaginationContext(config.pagination);
|
|
79
|
+
|
|
80
|
+
if (!hooks?.onToolCall) {
|
|
81
|
+
const stripped = findToolsWithReservedArguments(config.tools ?? {});
|
|
82
|
+
if (stripped.size > 0) {
|
|
83
|
+
const summary = [...stripped.entries()]
|
|
84
|
+
.map(([tool, keys]) => `${tool} (${keys.join(", ")})`)
|
|
85
|
+
.join("; ");
|
|
86
|
+
console.warn(
|
|
87
|
+
`[convex-mcp] tools declare reserved \`_*\` args but no onToolCall hook is configured. ` +
|
|
88
|
+
`These args are stripped from the published schema and will never be injected, ` +
|
|
89
|
+
`so every dispatched call will fail Convex validation. ` +
|
|
90
|
+
`Configure hooks.onToolCall to inject them via extendArgs. Affected tools: ${summary}`,
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function createServerAndTransport(
|
|
96
|
+
requestId: string,
|
|
97
|
+
convexToken?: string,
|
|
98
|
+
apiKey?: string,
|
|
99
|
+
): {
|
|
100
|
+
mcpServer: McpServer;
|
|
101
|
+
transport: WebStandardStreamableHTTPServerTransport;
|
|
102
|
+
} {
|
|
103
|
+
const mcpServer = new McpServer({
|
|
104
|
+
name: serverName,
|
|
105
|
+
version: serverVersion,
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
let client: ConvexClient;
|
|
109
|
+
if (injectedClient) {
|
|
110
|
+
client = injectedClient;
|
|
111
|
+
} else {
|
|
112
|
+
/* v8 ignore start -- configuration validation guarantees a URL when no client is injected */
|
|
113
|
+
if (!resolvedConvexUrl)
|
|
114
|
+
throw new Error("Convex URL not found after configuration validation.");
|
|
115
|
+
/* v8 ignore stop */
|
|
116
|
+
client = createDefaultClient(resolvedConvexUrl, convexToken);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
registerTools(mcpServer, client, prepared, hooks, requestId, apiKey);
|
|
120
|
+
registerResources(mcpServer, client, preparedRes);
|
|
121
|
+
|
|
122
|
+
// CRITICAL: Override MUST happen AFTER registerTools() — McpServer's lazy-init
|
|
123
|
+
// registers the default tools/list handler on the first tool() call.
|
|
124
|
+
// Overriding before would cause assertCanSetRequestHandler to throw.
|
|
125
|
+
const hasTools = prepared.length > 0;
|
|
126
|
+
if (hasTools && paginationCtx.enabled) {
|
|
127
|
+
const getAllTools = getOriginalToolsList(mcpServer);
|
|
128
|
+
registerPaginationHandlers(
|
|
129
|
+
mcpServer,
|
|
130
|
+
getAllTools,
|
|
131
|
+
paginationCtx.pageSize,
|
|
132
|
+
paginationCtx.secret,
|
|
133
|
+
);
|
|
134
|
+
if (paginationCtx.twoPhaseDiscovery) {
|
|
135
|
+
registerTwoPhaseHandlers(
|
|
136
|
+
mcpServer,
|
|
137
|
+
getAllTools,
|
|
138
|
+
paginationCtx.pageSize,
|
|
139
|
+
paginationCtx.secret,
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
145
|
+
sessionIdGenerator: undefined,
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
return { mcpServer, transport };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return {
|
|
152
|
+
handler() {
|
|
153
|
+
return {
|
|
154
|
+
async GET(request: Request): Promise<Response> {
|
|
155
|
+
const requestId = crypto.randomUUID();
|
|
156
|
+
const authResult = await validateRequest(request, config.auth);
|
|
157
|
+
if (!authResult.valid)
|
|
158
|
+
return addRequestId(authResult.response, requestId);
|
|
159
|
+
|
|
160
|
+
const { mcpServer, transport } = createServerAndTransport(
|
|
161
|
+
requestId,
|
|
162
|
+
authResult.convexToken,
|
|
163
|
+
authResult.apiKey,
|
|
164
|
+
);
|
|
165
|
+
await mcpServer.connect(transport);
|
|
166
|
+
const response = await transport.handleRequest(request);
|
|
167
|
+
return addRequestId(response, requestId);
|
|
168
|
+
},
|
|
169
|
+
async POST(request: Request): Promise<Response> {
|
|
170
|
+
const requestId = crypto.randomUUID();
|
|
171
|
+
const authResult = await validateRequest(request, config.auth);
|
|
172
|
+
if (!authResult.valid)
|
|
173
|
+
return addRequestId(authResult.response, requestId);
|
|
174
|
+
|
|
175
|
+
const contentType = request.headers.get("content-type");
|
|
176
|
+
if (!contentType?.includes("application/json")) {
|
|
177
|
+
return addRequestId(
|
|
178
|
+
new Response(
|
|
179
|
+
JSON.stringify({
|
|
180
|
+
error: {
|
|
181
|
+
code: -32_700,
|
|
182
|
+
message:
|
|
183
|
+
"Unsupported Media Type: expected application/json",
|
|
184
|
+
},
|
|
185
|
+
id: null,
|
|
186
|
+
jsonrpc: "2.0",
|
|
187
|
+
}),
|
|
188
|
+
{
|
|
189
|
+
headers: { "Content-Type": "application/json" },
|
|
190
|
+
status: 415,
|
|
191
|
+
},
|
|
192
|
+
),
|
|
193
|
+
requestId,
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const { mcpServer, transport } = createServerAndTransport(
|
|
198
|
+
requestId,
|
|
199
|
+
authResult.convexToken,
|
|
200
|
+
authResult.apiKey,
|
|
201
|
+
);
|
|
202
|
+
await mcpServer.connect(transport);
|
|
203
|
+
const response = await transport.handleRequest(request);
|
|
204
|
+
return addRequestId(response, requestId);
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { ConvexValidator } from "../types.js";
|
|
2
|
+
|
|
3
|
+
import type { CallContext, HookReturn, ToolDef } from "./types.js";
|
|
4
|
+
|
|
5
|
+
type ToolOptions = {
|
|
6
|
+
args?: ConvexValidator;
|
|
7
|
+
description?: string;
|
|
8
|
+
onError?: (ctx: CallContext & { phase: "error" }) => HookReturn;
|
|
9
|
+
tags?: Record<string, string>;
|
|
10
|
+
timeout?: number;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export function query(ref: unknown, options: ToolOptions = {}): ToolDef {
|
|
14
|
+
return {
|
|
15
|
+
args: options.args,
|
|
16
|
+
description: options.description,
|
|
17
|
+
onError: options.onError,
|
|
18
|
+
ref,
|
|
19
|
+
tags: options.tags,
|
|
20
|
+
timeout: options.timeout,
|
|
21
|
+
type: "query",
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function mutation(ref: unknown, options: ToolOptions = {}): ToolDef {
|
|
26
|
+
return {
|
|
27
|
+
args: options.args,
|
|
28
|
+
description: options.description,
|
|
29
|
+
onError: options.onError,
|
|
30
|
+
ref,
|
|
31
|
+
tags: options.tags,
|
|
32
|
+
timeout: options.timeout,
|
|
33
|
+
type: "mutation",
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function action(ref: unknown, options: ToolOptions = {}): ToolDef {
|
|
38
|
+
return {
|
|
39
|
+
args: options.args,
|
|
40
|
+
description: options.description,
|
|
41
|
+
onError: options.onError,
|
|
42
|
+
ref,
|
|
43
|
+
tags: options.tags,
|
|
44
|
+
timeout: options.timeout,
|
|
45
|
+
type: "action",
|
|
46
|
+
};
|
|
47
|
+
}
|