@decocms/runtime 1.0.0-alpha.10 → 1.0.0-alpha.12

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/src/tools.ts ADDED
@@ -0,0 +1,342 @@
1
+ /* oxlint-disable no-explicit-any */
2
+ /* oxlint-disable ban-types */
3
+ import { HttpServerTransport } from "@deco/mcp/http";
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { z } from "zod";
6
+ import { zodToJsonSchema } from "zod-to-json-schema";
7
+ import type { DefaultEnv } from "./index.ts";
8
+ import { State } from "./state.ts";
9
+
10
+ export const createRuntimeContext = (prev?: AppContext) => {
11
+ const store = State.getStore();
12
+ if (!store) {
13
+ if (prev) {
14
+ return prev;
15
+ }
16
+ throw new Error("Missing context, did you forget to call State.bind?");
17
+ }
18
+ return store;
19
+ };
20
+
21
+ export interface ToolExecutionContext<
22
+ TSchemaIn extends z.ZodTypeAny = z.ZodTypeAny,
23
+ > {
24
+ context: z.infer<TSchemaIn>;
25
+ runtimeContext: AppContext;
26
+ }
27
+
28
+ /**
29
+ * Tool interface with generic schema types for type-safe tool creation.
30
+ */
31
+ export interface Tool<
32
+ TSchemaIn extends z.ZodTypeAny = z.ZodTypeAny,
33
+ TSchemaOut extends z.ZodTypeAny | undefined = undefined,
34
+ > {
35
+ id: string;
36
+ description?: string;
37
+ inputSchema: TSchemaIn;
38
+ outputSchema?: TSchemaOut;
39
+ execute(
40
+ context: ToolExecutionContext<TSchemaIn>,
41
+ ): TSchemaOut extends z.ZodSchema
42
+ ? Promise<z.infer<TSchemaOut>>
43
+ : Promise<unknown>;
44
+ }
45
+
46
+ /**
47
+ * Streamable tool interface for tools that return Response streams.
48
+ */
49
+ export interface StreamableTool<TSchemaIn extends z.ZodSchema = z.ZodSchema> {
50
+ id: string;
51
+ inputSchema: TSchemaIn;
52
+ streamable?: true;
53
+ description?: string;
54
+ execute(input: ToolExecutionContext<TSchemaIn>): Promise<Response>;
55
+ }
56
+
57
+ /**
58
+ * CreatedTool is a permissive type that any Tool or StreamableTool can be assigned to.
59
+ * Uses a structural type with relaxed execute signature to allow tools with any schema.
60
+ */
61
+ export type CreatedTool = {
62
+ id: string;
63
+ description?: string;
64
+ inputSchema: z.ZodTypeAny;
65
+ outputSchema?: z.ZodTypeAny;
66
+ streamable?: true;
67
+ // Use a permissive execute signature - accepts any context shape
68
+ execute(context: {
69
+ context: unknown;
70
+ runtimeContext: AppContext;
71
+ }): Promise<unknown>;
72
+ };
73
+
74
+ /**
75
+ * creates a private tool that always ensure for athentication before being executed
76
+ */
77
+ export function createPrivateTool<
78
+ TSchemaIn extends z.ZodSchema = z.ZodSchema,
79
+ TSchemaOut extends z.ZodSchema | undefined = undefined,
80
+ >(opts: Tool<TSchemaIn, TSchemaOut>): Tool<TSchemaIn, TSchemaOut> {
81
+ const execute = opts.execute;
82
+ if (typeof execute === "function") {
83
+ opts.execute = (input: ToolExecutionContext<TSchemaIn>) => {
84
+ const env = input.runtimeContext.env;
85
+ if (env) {
86
+ env.MESH_REQUEST_CONTEXT?.ensureAuthenticated();
87
+ }
88
+ return execute(input);
89
+ };
90
+ }
91
+ return createTool(opts);
92
+ }
93
+
94
+ export function createStreamableTool<
95
+ TSchemaIn extends z.ZodSchema = z.ZodSchema,
96
+ >(streamableTool: StreamableTool<TSchemaIn>): StreamableTool<TSchemaIn> {
97
+ return {
98
+ ...streamableTool,
99
+ execute: (input: ToolExecutionContext<TSchemaIn>) => {
100
+ const env = input.runtimeContext.env;
101
+ if (env) {
102
+ env.MESH_REQUEST_CONTEXT?.ensureAuthenticated();
103
+ }
104
+ return streamableTool.execute({
105
+ ...input,
106
+ runtimeContext: createRuntimeContext(input.runtimeContext),
107
+ });
108
+ },
109
+ };
110
+ }
111
+
112
+ export function createTool<
113
+ TSchemaIn extends z.ZodSchema = z.ZodSchema,
114
+ TSchemaOut extends z.ZodSchema | undefined = undefined,
115
+ >(opts: Tool<TSchemaIn, TSchemaOut>): Tool<TSchemaIn, TSchemaOut> {
116
+ return {
117
+ ...opts,
118
+ execute: (input: ToolExecutionContext<TSchemaIn>) => {
119
+ return opts.execute({
120
+ ...input,
121
+ runtimeContext: createRuntimeContext(input.runtimeContext),
122
+ });
123
+ },
124
+ };
125
+ }
126
+
127
+ export interface ViewExport {
128
+ title: string;
129
+ icon: string;
130
+ url: string;
131
+ tools?: string[];
132
+ rules?: string[];
133
+ installBehavior?: "none" | "open" | "autoPin";
134
+ }
135
+
136
+ export interface Integration {
137
+ id: string;
138
+ appId: string;
139
+ }
140
+
141
+ export function isStreamableTool(
142
+ tool: CreatedTool,
143
+ ): tool is StreamableTool & CreatedTool {
144
+ return tool && "streamable" in tool && tool.streamable === true;
145
+ }
146
+
147
+ export interface CreateMCPServerOptions<
148
+ Env = unknown,
149
+ TSchema extends z.ZodTypeAny = never,
150
+ > {
151
+ before?: (env: Env & DefaultEnv<TSchema>) => Promise<void> | void;
152
+ configuration?: {
153
+ state?: TSchema;
154
+ scopes?: string[];
155
+ };
156
+ tools?:
157
+ | Array<
158
+ (
159
+ env: Env & DefaultEnv<TSchema>,
160
+ ) =>
161
+ | Promise<CreatedTool>
162
+ | CreatedTool
163
+ | CreatedTool[]
164
+ | Promise<CreatedTool[]>
165
+ >
166
+ | ((
167
+ env: Env & DefaultEnv<TSchema>,
168
+ ) => CreatedTool[] | Promise<CreatedTool[]>);
169
+ }
170
+
171
+ export type Fetch<TEnv = unknown> = (
172
+ req: Request,
173
+ env: TEnv,
174
+ ctx: ExecutionContext,
175
+ ) => Promise<Response> | Response;
176
+
177
+ export interface AppContext<TEnv extends DefaultEnv = DefaultEnv> {
178
+ env: TEnv;
179
+ ctx: { waitUntil: (promise: Promise<unknown>) => void };
180
+ req?: Request;
181
+ }
182
+
183
+ const decoChatOAuthToolsFor = <TSchema extends z.ZodTypeAny = never>({
184
+ state: schema,
185
+ scopes,
186
+ }: CreateMCPServerOptions<
187
+ unknown,
188
+ TSchema
189
+ >["configuration"] = {}): CreatedTool[] => {
190
+ const jsonSchema = schema
191
+ ? zodToJsonSchema(schema)
192
+ : { type: "object", properties: {} };
193
+ return [
194
+ // MESH API support
195
+ createTool({
196
+ id: "MCP_CONFIGURATION",
197
+ description: "MCP Configuration",
198
+ inputSchema: z.object({}),
199
+ outputSchema: z.object({
200
+ stateSchema: z.unknown(),
201
+ scopes: z.array(z.string()).optional(),
202
+ }),
203
+ execute: () => {
204
+ return Promise.resolve({
205
+ stateSchema: jsonSchema,
206
+ scopes,
207
+ });
208
+ },
209
+ }),
210
+ ];
211
+ };
212
+
213
+ type CallTool = (opts: {
214
+ toolCallId: string;
215
+ toolCallInput: unknown;
216
+ }) => Promise<unknown>;
217
+
218
+ export type MCPServer<TEnv = unknown, TSchema extends z.ZodTypeAny = never> = {
219
+ fetch: Fetch<TEnv & DefaultEnv<TSchema>>;
220
+ callTool: CallTool;
221
+ };
222
+
223
+ export const createMCPServer = <
224
+ TEnv = unknown,
225
+ TSchema extends z.ZodTypeAny = never,
226
+ >(
227
+ options: CreateMCPServerOptions<TEnv, TSchema>,
228
+ ): MCPServer<TEnv, TSchema> => {
229
+ const createServer = async (bindings: TEnv & DefaultEnv<TSchema>) => {
230
+ await options.before?.(bindings);
231
+
232
+ const server = new McpServer(
233
+ { name: "@deco/mcp-api", version: "1.0.0" },
234
+ { capabilities: { tools: {} } },
235
+ );
236
+
237
+ const toolsFn =
238
+ typeof options.tools === "function"
239
+ ? options.tools
240
+ : async (bindings: TEnv & DefaultEnv<TSchema>) => {
241
+ if (typeof options.tools === "function") {
242
+ return await options.tools(bindings);
243
+ }
244
+ return await Promise.all(
245
+ options.tools?.flatMap(async (tool) => {
246
+ const toolResult = tool(bindings);
247
+ const awaited = await toolResult;
248
+ if (Array.isArray(awaited)) {
249
+ return awaited;
250
+ }
251
+ return [awaited];
252
+ }) ?? [],
253
+ ).then((t) => t.flat());
254
+ };
255
+ const tools = await toolsFn(bindings);
256
+
257
+ tools.push(...decoChatOAuthToolsFor<TSchema>(options.configuration));
258
+
259
+ for (const tool of tools) {
260
+ server.registerTool(
261
+ tool.id,
262
+ {
263
+ _meta: {
264
+ streamable: isStreamableTool(tool),
265
+ },
266
+ description: tool.description,
267
+ inputSchema:
268
+ tool.inputSchema && "shape" in tool.inputSchema
269
+ ? (tool.inputSchema.shape as z.ZodRawShape)
270
+ : z.object({}).shape,
271
+ outputSchema: isStreamableTool(tool)
272
+ ? z.object({ bytes: z.record(z.string(), z.number()) }).shape
273
+ : tool.outputSchema &&
274
+ typeof tool.outputSchema === "object" &&
275
+ "shape" in tool.outputSchema
276
+ ? (tool.outputSchema.shape as z.ZodRawShape)
277
+ : z.object({}).shape,
278
+ },
279
+ async (args) => {
280
+ let result = await tool.execute({
281
+ context: args,
282
+ runtimeContext: createRuntimeContext(),
283
+ });
284
+
285
+ if (isStreamableTool(tool) && result instanceof Response) {
286
+ result = { bytes: await result.bytes() };
287
+ }
288
+ return {
289
+ structuredContent: result as Record<string, unknown>,
290
+ content: [
291
+ {
292
+ type: "text",
293
+ text: JSON.stringify(result),
294
+ },
295
+ ],
296
+ };
297
+ },
298
+ );
299
+ }
300
+
301
+ return { server, tools };
302
+ };
303
+
304
+ const fetch = async (
305
+ req: Request,
306
+ env: TEnv & DefaultEnv<TSchema>,
307
+ _ctx: ExecutionContext,
308
+ ) => {
309
+ const { server } = await createServer(env);
310
+ const transport = new HttpServerTransport();
311
+
312
+ await server.connect(transport);
313
+
314
+ return await transport.handleMessage(req);
315
+ };
316
+
317
+ const callTool: CallTool = async ({ toolCallId, toolCallInput }) => {
318
+ const currentState = State.getStore();
319
+ if (!currentState) {
320
+ throw new Error("Missing state, did you forget to call State.bind?");
321
+ }
322
+ const env = currentState?.env;
323
+ const { tools } = await createServer(env as TEnv & DefaultEnv<TSchema>);
324
+ const tool = tools.find((t) => t.id === toolCallId);
325
+ const execute = tool?.execute;
326
+ if (!execute) {
327
+ throw new Error(
328
+ `Tool ${toolCallId} not found or does not have an execute function`,
329
+ );
330
+ }
331
+
332
+ return execute({
333
+ context: toolCallInput,
334
+ runtimeContext: createRuntimeContext(),
335
+ });
336
+ };
337
+
338
+ return {
339
+ fetch,
340
+ callTool,
341
+ };
342
+ };
package/src/wrangler.ts CHANGED
@@ -2,20 +2,20 @@ export interface BindingBase {
2
2
  name: string;
3
3
  }
4
4
 
5
- export interface MCPIntegrationIdBinding extends BindingBase {
5
+ export interface MCPConnectionBinding extends BindingBase {
6
6
  type: "mcp";
7
7
  /**
8
8
  * If not provided, will return a function that takes the integration id and return the binding implementation..
9
9
  */
10
- integration_id: string;
10
+ connection_id: string;
11
11
  }
12
12
 
13
- export interface MCPIntegrationNameBinding extends BindingBase {
13
+ export interface MCPAppBinding extends BindingBase {
14
14
  type: "mcp";
15
15
  /**
16
16
  * The name of the integration to bind.
17
17
  */
18
- integration_name: string;
18
+ app_name: string;
19
19
  }
20
20
  export interface ContractClause {
21
21
  id: string;
@@ -36,7 +36,7 @@ export interface ContractBinding extends BindingBase {
36
36
  contract: Contract;
37
37
  }
38
38
 
39
- export type MCPBinding = MCPIntegrationIdBinding | MCPIntegrationNameBinding;
39
+ export type MCPBinding = MCPConnectionBinding | MCPAppBinding;
40
40
 
41
41
  export type Binding = MCPBinding | ContractBinding;
42
42
 
package/tsconfig.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "extends": "../../tsconfig.json",
3
3
  "compilerOptions": {
4
- "types": ["@cloudflare/workers-types"]
4
+ "types": ["@cloudflare/workers-types", "@types/node"]
5
5
  },
6
6
  "include": ["src/**/*"],
7
7
  "exclude": ["node_modules", "dist", "scripts/**/*"]
package/src/admin.ts DELETED
@@ -1,16 +0,0 @@
1
- import { createChannel } from "bidc";
2
-
3
- export const requestMissingScopes = ({ scopes }: { scopes: string[] }) => {
4
- try {
5
- const channel = createChannel();
6
- channel.send({
7
- type: "request_missing_scopes",
8
- payload: {
9
- scopes,
10
- },
11
- });
12
- channel.cleanup();
13
- } catch (error) {
14
- console.error("Failed to request missing scopes", error);
15
- }
16
- };
package/src/auth.ts DELETED
@@ -1,233 +0,0 @@
1
- import { JWK, jwtVerify } from "jose";
2
- import type { DefaultEnv } from "./index.ts";
3
-
4
- const DECO_APP_AUTH_COOKIE_NAME = "deco_page_auth";
5
- const MAX_COOKIE_SIZE = 4000; // Leave some buffer below the 4096 limit
6
-
7
- export interface State {
8
- next?: string;
9
- }
10
-
11
- export const StateParser = {
12
- parse: (state: string) => {
13
- return JSON.parse(decodeURIComponent(atob(state))) as State;
14
- },
15
- stringify: (state: State) => {
16
- return btoa(encodeURIComponent(JSON.stringify(state)));
17
- },
18
- };
19
-
20
- // Helper function to chunk a value into multiple cookies
21
- const chunkValue = (value: string): string[] => {
22
- if (value.length <= MAX_COOKIE_SIZE) {
23
- return [value];
24
- }
25
-
26
- const chunks: string[] = [];
27
- for (let i = 0; i < value.length; i += MAX_COOKIE_SIZE) {
28
- chunks.push(value.slice(i, i + MAX_COOKIE_SIZE));
29
- }
30
- return chunks;
31
- };
32
-
33
- // Helper function to reassemble chunked cookies
34
- const reassembleChunkedCookies = (
35
- cookies: Record<string, string>,
36
- baseName: string,
37
- ): string | undefined => {
38
- // First try the base cookie (non-chunked)
39
- if (cookies[baseName]) {
40
- return cookies[baseName];
41
- }
42
-
43
- // Try to reassemble from chunks
44
- const chunks: string[] = [];
45
- let index = 0;
46
-
47
- while (true) {
48
- const chunkName = `${baseName}_${index}`;
49
- if (!cookies[chunkName]) {
50
- break;
51
- }
52
- chunks.push(cookies[chunkName]);
53
- index++;
54
- }
55
-
56
- return chunks.length > 0 ? chunks.join("") : undefined;
57
- };
58
-
59
- // Helper function to parse cookies from request
60
- const parseCookies = (cookieHeader: string): Record<string, string> => {
61
- const cookies: Record<string, string> = {};
62
- if (!cookieHeader) return cookies;
63
-
64
- cookieHeader.split(";").forEach((cookie) => {
65
- const [name, ...rest] = cookie.trim().split("=");
66
- if (name && rest.length > 0) {
67
- cookies[name] = decodeURIComponent(rest.join("="));
68
- }
69
- });
70
-
71
- return cookies;
72
- };
73
-
74
- const parseJWK = (jwk: string): JWK => JSON.parse(atob(jwk)) as JWK;
75
-
76
- export const getReqToken = async (req: Request, env: DefaultEnv) => {
77
- const token = () => {
78
- // First try to get token from Authorization header
79
- const authHeader = req.headers.get("Authorization");
80
- if (authHeader) {
81
- return authHeader.split(" ")[1];
82
- }
83
-
84
- // If not found, try to get from cookie
85
- const cookieHeader = req.headers.get("Cookie");
86
- if (cookieHeader) {
87
- const cookies = parseCookies(cookieHeader);
88
- return reassembleChunkedCookies(cookies, DECO_APP_AUTH_COOKIE_NAME);
89
- }
90
-
91
- return undefined;
92
- };
93
-
94
- const authToken = token();
95
- if (!authToken) {
96
- return undefined;
97
- }
98
-
99
- env.DECO_API_JWT_PUBLIC_KEY &&
100
- (await jwtVerify(authToken, parseJWK(env.DECO_API_JWT_PUBLIC_KEY), {
101
- issuer: "https://api.decocms.com",
102
- algorithms: ["RS256"],
103
- typ: "JWT",
104
- }).catch((err) => {
105
- console.error(
106
- `[auth-token]: error validating: ${err} ${env.DECO_API_JWT_PUBLIC_KEY}`,
107
- );
108
- }));
109
-
110
- return authToken;
111
- };
112
-
113
- export interface AuthCallbackOptions {
114
- apiUrl?: string;
115
- appName: string;
116
- }
117
-
118
- export const handleAuthCallback = async (
119
- req: Request,
120
- options: AuthCallbackOptions,
121
- ): Promise<Response> => {
122
- const url = new URL(req.url);
123
- const code = url.searchParams.get("code");
124
- const state = url.searchParams.get("state");
125
-
126
- if (!code) {
127
- return new Response("Missing authorization code", { status: 400 });
128
- }
129
-
130
- // Parse state to get the next URL
131
- let next = "/";
132
- if (state) {
133
- try {
134
- const parsedState = StateParser.parse(state);
135
- next = parsedState.next || "/";
136
- } catch {
137
- // ignore parse errors
138
- }
139
- }
140
-
141
- try {
142
- // Exchange code for token
143
- const apiUrl = options.apiUrl ?? "https://api.decocms.com";
144
- const exchangeResponse = await fetch(`${apiUrl}/apps/code-exchange`, {
145
- method: "POST",
146
- headers: {
147
- "Content-Type": "application/json",
148
- },
149
- body: JSON.stringify({
150
- code,
151
- client_id: options.appName,
152
- }),
153
- });
154
-
155
- if (!exchangeResponse.ok) {
156
- console.error(
157
- "authentication failed",
158
- code,
159
- options.appName,
160
- await exchangeResponse.text().catch((_) => ""),
161
- );
162
- return new Response("Authentication failed", { status: 401 });
163
- }
164
-
165
- const { access_token } = (await exchangeResponse.json()) as {
166
- access_token: string;
167
- };
168
-
169
- if (!access_token) {
170
- return new Response("No access token received", { status: 401 });
171
- }
172
-
173
- // Chunk the token if it's too large
174
- const chunks = chunkValue(access_token);
175
- const headers = new Headers();
176
- headers.set("Location", next);
177
-
178
- // Set cookies for each chunk
179
- if (chunks.length === 1) {
180
- // Single cookie for small tokens
181
- headers.set(
182
- "Set-Cookie",
183
- `${DECO_APP_AUTH_COOKIE_NAME}=${access_token}; HttpOnly; SameSite=None; Secure; Path=/`,
184
- );
185
- } else {
186
- // Multiple cookies for large tokens
187
- chunks.forEach((chunk, index) => {
188
- headers.append(
189
- "Set-Cookie",
190
- `${DECO_APP_AUTH_COOKIE_NAME}_${index}=${chunk}; HttpOnly; SameSite=None; Secure; Path=/`,
191
- );
192
- });
193
- }
194
-
195
- return new Response(null, {
196
- status: 302,
197
- headers,
198
- });
199
- } catch (err) {
200
- return new Response(`Authentication failed ${err}`, { status: 500 });
201
- }
202
- };
203
-
204
- const removeAuthCookie = (headers: Headers) => {
205
- // Clear the base cookie
206
- headers.append(
207
- "Set-Cookie",
208
- `${DECO_APP_AUTH_COOKIE_NAME}=; HttpOnly; SameSite=None; Secure; Path=/; Max-Age=0`,
209
- );
210
-
211
- // Clear all potential chunked cookies
212
- // We'll try to clear up to 10 chunks (which would support tokens up to 40KB)
213
- // This is a reasonable upper limit
214
- for (let i = 0; i < 10; i++) {
215
- headers.append(
216
- "Set-Cookie",
217
- `${DECO_APP_AUTH_COOKIE_NAME}_${i}=; HttpOnly; SameSite=None; Secure; Path=/; Max-Age=0`,
218
- );
219
- }
220
- };
221
-
222
- export const handleLogout = (req: Request) => {
223
- const url = new URL(req.url);
224
- const next = url.searchParams.get("next");
225
- const redirectTo = new URL("/", url);
226
- const headers = new Headers();
227
- removeAuthCookie(headers);
228
- headers.set("Location", next ?? redirectTo.href);
229
- return new Response(null, {
230
- status: 302,
231
- headers,
232
- });
233
- };