@genkit-ai/mcp 1.14.1-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +203 -0
  2. package/README.md +205 -0
  3. package/examples/client/index.js +36 -0
  4. package/examples/client/package.json +25 -0
  5. package/examples/server/index.js +46 -0
  6. package/examples/server/package.json +18 -0
  7. package/examples/server/prompts/port_code.prompt +13 -0
  8. package/lib/client/client.d.mts +177 -0
  9. package/lib/client/client.d.ts +177 -0
  10. package/lib/client/client.js +282 -0
  11. package/lib/client/client.js.map +1 -0
  12. package/lib/client/client.mjs +267 -0
  13. package/lib/client/client.mjs.map +1 -0
  14. package/lib/client/host.d.mts +202 -0
  15. package/lib/client/host.d.ts +202 -0
  16. package/lib/client/host.js +392 -0
  17. package/lib/client/host.js.map +1 -0
  18. package/lib/client/host.mjs +368 -0
  19. package/lib/client/host.mjs.map +1 -0
  20. package/lib/client/index.d.mts +9 -0
  21. package/lib/client/index.d.ts +9 -0
  22. package/lib/client/index.js +32 -0
  23. package/lib/client/index.js.map +1 -0
  24. package/lib/client/index.mjs +7 -0
  25. package/lib/client/index.mjs.map +1 -0
  26. package/lib/index.d.mts +12 -0
  27. package/lib/index.d.ts +12 -0
  28. package/lib/index.js +48 -0
  29. package/lib/index.js.map +1 -0
  30. package/lib/index.mjs +22 -0
  31. package/lib/index.mjs.map +1 -0
  32. package/lib/server.d.mts +188 -0
  33. package/lib/server.d.ts +188 -0
  34. package/lib/server.js +280 -0
  35. package/lib/server.js.map +1 -0
  36. package/lib/server.mjs +249 -0
  37. package/lib/server.mjs.map +1 -0
  38. package/lib/util/index.d.mts +11 -0
  39. package/lib/util/index.d.ts +11 -0
  40. package/lib/util/index.js +29 -0
  41. package/lib/util/index.js.map +1 -0
  42. package/lib/util/index.mjs +5 -0
  43. package/lib/util/index.mjs.map +1 -0
  44. package/lib/util/message.d.mts +43 -0
  45. package/lib/util/message.d.ts +43 -0
  46. package/lib/util/message.js +61 -0
  47. package/lib/util/message.js.map +1 -0
  48. package/lib/util/message.mjs +36 -0
  49. package/lib/util/message.mjs.map +1 -0
  50. package/lib/util/prompts.d.mts +45 -0
  51. package/lib/util/prompts.d.ts +45 -0
  52. package/lib/util/prompts.js +147 -0
  53. package/lib/util/prompts.js.map +1 -0
  54. package/lib/util/prompts.mjs +123 -0
  55. package/lib/util/prompts.mjs.map +1 -0
  56. package/lib/util/resource.d.mts +28 -0
  57. package/lib/util/resource.d.ts +28 -0
  58. package/lib/util/resource.js +116 -0
  59. package/lib/util/resource.js.map +1 -0
  60. package/lib/util/resource.mjs +95 -0
  61. package/lib/util/resource.mjs.map +1 -0
  62. package/lib/util/tools.d.mts +37 -0
  63. package/lib/util/tools.d.ts +37 -0
  64. package/lib/util/tools.js +120 -0
  65. package/lib/util/tools.js.map +1 -0
  66. package/lib/util/tools.mjs +95 -0
  67. package/lib/util/tools.mjs.map +1 -0
  68. package/lib/util/transport.d.mts +39 -0
  69. package/lib/util/transport.d.ts +39 -0
  70. package/lib/util/transport.js +63 -0
  71. package/lib/util/transport.js.map +1 -0
  72. package/lib/util/transport.mjs +29 -0
  73. package/lib/util/transport.mjs.map +1 -0
  74. package/package.json +57 -0
  75. package/src/client/client.ts +414 -0
  76. package/src/client/host.ts +485 -0
  77. package/src/client/index.ts +29 -0
  78. package/src/index.ts +114 -0
  79. package/src/server.ts +330 -0
  80. package/src/util/index.ts +20 -0
  81. package/src/util/message.ts +72 -0
  82. package/src/util/prompts.ts +223 -0
  83. package/src/util/resource.ts +141 -0
  84. package/src/util/tools.ts +164 -0
  85. package/src/util/transport.ts +67 -0
  86. package/tests/fakes.ts +221 -0
  87. package/tests/host_test.ts +609 -0
  88. package/tests/server_test.ts +165 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n GenkitError,\n Message,\n type Genkit,\n type MessageData,\n type PromptAction,\n} from 'genkit';\nimport type { McpServerOptions } from './index.js';\n\nimport type { Server } from '@modelcontextprotocol/sdk/server/index.js' with { 'resolution-mode': 'import' };\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js' with { 'resolution-mode': 'import' };\nimport type {\n CallToolRequest,\n CallToolResult,\n GetPromptRequest,\n GetPromptResult,\n ListPromptsRequest,\n ListPromptsResult,\n ListToolsRequest,\n ListToolsResult,\n Prompt,\n PromptMessage,\n Tool,\n} from '@modelcontextprotocol/sdk/types.js' with { 'resolution-mode': 'import' };\nimport { logger } from 'genkit/logging';\nimport { toJsonSchema } from 'genkit/schema';\nimport { ToolAction, toToolDefinition } from 'genkit/tool';\n\n/**\n * Represents an MCP (Model Context Protocol) server that exposes Genkit tools\n * and prompts. This class wraps a Genkit instance and makes its registered\n * actions (tools, prompts) available to MCP clients. It handles the translation\n * between Genkit's action definitions and MCP's expected formats.\n */\nexport class GenkitMcpServer {\n ai: Genkit;\n options: McpServerOptions;\n server?: Server;\n actionsResolved = false;\n toolActions: ToolAction[] = [];\n promptActions: PromptAction[] = [];\n\n /**\n * Creates an instance of GenkitMcpServer.\n * @param ai The Genkit instance whose actions will be exposed.\n * @param options Configuration options for the MCP server, like its name and version.\n */\n constructor(ai: Genkit, options: McpServerOptions) {\n this.ai = ai;\n this.options = options;\n }\n\n /**\n * Initializes the MCP server instance and registers request handlers. It\n * dynamically imports MCP SDK components and sets up handlers for listing\n * tools, calling tools, listing prompts, and getting prompts. It also\n * resolves and stores all tool and prompt actions from the Genkit instance.\n *\n * This method is called by the constructor and ensures the server is ready\n * before any requests are handled. It's idempotent.\n */\n async setup(): Promise<void> {\n if (this.actionsResolved) return;\n const { Server } = await import(\n '@modelcontextprotocol/sdk/server/index.js'\n );\n\n this.server = new Server(\n { name: this.options.name, version: this.options.version || '1.0.0' },\n {\n capabilities: {\n prompts: {},\n tools: {},\n },\n }\n );\n\n const {\n CallToolRequestSchema,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListToolsRequestSchema,\n } = await import('@modelcontextprotocol/sdk/types.js');\n\n this.server.setRequestHandler(\n ListToolsRequestSchema,\n this.listTools.bind(this)\n );\n this.server.setRequestHandler(\n CallToolRequestSchema,\n this.callTool.bind(this)\n );\n this.server.setRequestHandler(\n ListPromptsRequestSchema,\n this.listPrompts.bind(this)\n );\n this.server.setRequestHandler(\n GetPromptRequestSchema,\n this.getPrompt.bind(this)\n );\n\n // TODO -- use listResolvableActions.\n const allActions = await this.ai.registry.listActions();\n const toolList: ToolAction[] = [];\n const promptList: PromptAction[] = [];\n for (const k in allActions) {\n if (k.startsWith('/tool/')) {\n toolList.push(allActions[k] as ToolAction);\n } else if (k.startsWith('/prompt/')) {\n promptList.push(allActions[k] as PromptAction);\n }\n }\n this.toolActions = toolList;\n this.promptActions = promptList;\n this.actionsResolved = true;\n }\n\n /**\n * Handles MCP requests to list available tools.\n * It maps the resolved Genkit tool actions to the MCP Tool format.\n * @param req The MCP ListToolsRequest.\n * @returns A Promise resolving to an MCP ListToolsResult.\n */\n async listTools(req: ListToolsRequest): Promise<ListToolsResult> {\n await this.setup();\n return {\n tools: this.toolActions.map((t): Tool => {\n const def = toToolDefinition(t);\n return {\n name: def.name,\n inputSchema: (def.inputSchema as any) || { type: 'object' },\n description: def.description,\n _meta: t.__action.metadata?.mcp?._meta,\n };\n }),\n };\n }\n\n /**\n * Handles MCP requests to call a specific tool. It finds the corresponding\n * Genkit tool action and executes it with the provided arguments. The result\n * is then formatted as an MCP CallToolResult.\n * @param req The MCP CallToolRequest containing the tool name and arguments.\n * @returns A Promise resolving to an MCP CallToolResult.\n * @throws GenkitError if the requested tool is not found.\n */\n async callTool(req: CallToolRequest): Promise<CallToolResult> {\n await this.setup();\n const tool = this.toolActions.find(\n (t) => t.__action.name === req.params.name\n );\n if (!tool)\n throw new GenkitError({\n status: 'NOT_FOUND',\n message: `Tried to call tool '${req.params.name}' but it could not be found.`,\n });\n const result = await tool(req.params.arguments);\n return {\n content: [\n {\n type: 'text',\n text: typeof result === 'string' ? result : JSON.stringify(result),\n },\n ],\n };\n }\n\n /**\n * Handles MCP requests to list available prompts.\n * It maps the resolved Genkit prompt actions to the MCP Prompt format,\n * including converting input schemas to MCP argument definitions.\n * @param req The MCP ListPromptsRequest.\n * @returns A Promise resolving to an MCP ListPromptsResult.\n */\n async listPrompts(req: ListPromptsRequest): Promise<ListPromptsResult> {\n await this.setup();\n return {\n prompts: this.promptActions.map((p): Prompt => {\n return {\n name: p.__action.name,\n description: p.__action.description,\n arguments: toMcpPromptArguments(p),\n _meta: p.__action.metadata?.mcp?._meta,\n };\n }),\n };\n }\n\n /**\n * Handles MCP requests to get (render) a specific prompt. It finds the\n * corresponding Genkit prompt action, executes it with the provided\n * arguments, and then formats the resulting messages into the MCP\n * PromptMessage format.\n * @param req The MCP GetPromptRequest containing the prompt name and\n * arguments.\n * @returns A Promise resolving to an MCP GetPromptResult.\n * @throws GenkitError if the requested prompt is not found.\n */\n async getPrompt(req: GetPromptRequest): Promise<GetPromptResult> {\n await this.setup();\n const prompt = this.promptActions.find(\n (p) => p.__action.name === req.params.name\n );\n if (!prompt)\n throw new GenkitError({\n status: 'NOT_FOUND',\n message: `[MCP Server] Tried to call prompt '${req.params.name}' but it could not be found.`,\n });\n const result = await prompt(req.params.arguments);\n return {\n description: prompt.__action.description,\n messages: result.messages.map(toMcpPromptMessage),\n };\n }\n\n /**\n * Starts the MCP server with the specified transport or a default\n * StdioServerTransport. Ensures the server is set up before connecting the\n * transport.\n * @param transport Optional MCP transport instance. If not provided, a\n * StdioServerTransport will be created and used.\n */\n async start(transport?: Transport) {\n if (!transport) {\n const { StdioServerTransport } = await import(\n '@modelcontextprotocol/sdk/server/stdio.js'\n );\n transport = new StdioServerTransport();\n }\n await this.setup();\n await this.server!.connect(transport);\n logger.info(\n `[MCP Server] MCP server '${this.options.name}' started successfully.`\n );\n }\n}\n\n/**\n * Converts a Genkit prompt's input schema to an array of MCP prompt arguments.\n * MCP prompts currently only support string arguments.\n * @param p The Genkit PromptAction.\n * @returns An array of MCP prompt arguments, or undefined if the schema is not defined.\n * @throws GenkitError if the input schema is not an object or if any property is not a string.\n */\nfunction toMcpPromptArguments(\n p: PromptAction\n): Prompt['arguments'] | undefined {\n const jsonSchema = toJsonSchema({\n schema: p.__action.inputSchema,\n jsonSchema: p.__action.inputJsonSchema,\n });\n\n if (!jsonSchema) return undefined;\n if (!jsonSchema.properties)\n throw new GenkitError({\n status: 'FAILED_PRECONDITION',\n message: '[MCP Server] MCP prompts must take objects as input schema.',\n });\n\n const args: Prompt['arguments'] = [];\n for (const k in jsonSchema.properties) {\n const { type, description } = jsonSchema.properties[k];\n if (\n type !== 'string' &&\n (!Array.isArray(type) || !type.includes('string'))\n ) {\n throw new GenkitError({\n status: 'FAILED_PRECONDITION',\n message: `[MCP Server] MCP prompts may only take string arguments, but ${p.__action.name} has property '${k}' of type '${type}'.`,\n });\n }\n args.push({\n name: k,\n description,\n required: jsonSchema.required?.includes(k),\n });\n }\n return args;\n}\n\nconst ROLE_MAP = { model: 'assistant', user: 'user' } as const;\n\n/**\n * Converts a Genkit MessageData object to an MCP PromptMessage.\n * Handles mapping of roles and content types (text, image).\n * MCP only supports 'user' and 'assistant' (model) roles and base64 data images.\n * @param messageData The Genkit MessageData object.\n * @returns An MCP PromptMessage.\n * @throws GenkitError if the role is unsupported or if media is not a data URL.\n */\nfunction toMcpPromptMessage(messageData: MessageData): PromptMessage {\n if (messageData.role !== 'model' && messageData.role !== 'user') {\n throw new GenkitError({\n status: 'UNIMPLEMENTED',\n message: `[MCP Server] MCP prompt messages do not support role '${messageData.role}'. Only 'user' and 'model' messages are supported.`,\n });\n }\n const message = new Message(messageData);\n const common = { role: ROLE_MAP[messageData.role] };\n if (message.media) {\n const { url, contentType } = message.media;\n if (!url.startsWith('data:'))\n throw new GenkitError({\n status: 'UNIMPLEMENTED',\n message: `[MCP Server] MCP prompt messages only support base64 data images.`,\n });\n const mimeType =\n contentType || url.substring(url.indexOf(':')! + 1, url.indexOf(';'));\n const data = url.substring(url.indexOf(',') + 1);\n return { ...common, content: { type: 'image', mimeType, data } };\n } else {\n return { ...common, content: { type: 'text', text: message.text } };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,oBAMO;AAkBP,qBAAuB;AACvB,oBAA6B;AAC7B,kBAA6C;AAQtC,MAAM,gBAAgB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA,kBAAkB;AAAA,EAClB,cAA4B,CAAC;AAAA,EAC7B,gBAAgC,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOjC,YAAY,IAAY,SAA2B;AACjD,SAAK,KAAK;AACV,SAAK,UAAU;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,MAAM,QAAuB;AAC3B,QAAI,KAAK,gBAAiB;AAC1B,UAAM,EAAE,OAAO,IAAI,MAAM,OACvB,2CACF;AAEA,SAAK,SAAS,IAAI;AAAA,MAChB,EAAE,MAAM,KAAK,QAAQ,MAAM,SAAS,KAAK,QAAQ,WAAW,QAAQ;AAAA,MACpE;AAAA,QACE,cAAc;AAAA,UACZ,SAAS,CAAC;AAAA,UACV,OAAO,CAAC;AAAA,QACV;AAAA,MACF;AAAA,IACF;AAEA,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,IAAI,MAAM,OAAO,oCAAoC;AAErD,SAAK,OAAO;AAAA,MACV;A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,EACH;AACA,QAAM,UAAU,IAAI,sBAAQ,WAAW;AACvC,QAAM,SAAS,EAAE,MAAM,SAAS,YAAY,IAAI,EAAE;AAClD,MAAI,QAAQ,OAAO;AACjB,UAAM,EAAE,KAAK,YAAY,IAAI,QAAQ;AACrC,QAAI,CAAC,IAAI,WAAW,OAAO;AACzB,YAAM,IAAI,0BAAY;AAAA,QACpB,QAAQ;AAAA,QACR,SAAS;AAAA,MACX,CAAC;AACH,UAAM,WACJ,eAAe,IAAI,UAAU,IAAI,QAAQ,GAAG,IAAK,GAAG,IAAI,QAAQ,GAAG,CAAC;AACtE,UAAM,OAAO,IAAI,UAAU,IAAI,QAAQ,GAAG,IAAI,CAAC;AAC/C,WAAO,EAAE,GAAG,QAAQ,SAAS,EAAE,MAAM,SAAS,UAAU,KAAK,EAAE;AAAA,EACjE,OAAO;AACL,WAAO,EAAE,GAAG,QAAQ,SAAS,EAAE,MAAM,QAAQ,MAAM,QAAQ,KAAK,EAAE;AAAA,EACpE;AACF;","names":[]}
package/lib/server.mjs ADDED
@@ -0,0 +1,249 @@
1
+ import {
2
+ GenkitError,
3
+ Message
4
+ } from "genkit";
5
+ import { logger } from "genkit/logging";
6
+ import { toJsonSchema } from "genkit/schema";
7
+ import { toToolDefinition } from "genkit/tool";
8
+ class GenkitMcpServer {
9
+ ai;
10
+ options;
11
+ server;
12
+ actionsResolved = false;
13
+ toolActions = [];
14
+ promptActions = [];
15
+ /**
16
+ * Creates an instance of GenkitMcpServer.
17
+ * @param ai The Genkit instance whose actions will be exposed.
18
+ * @param options Configuration options for the MCP server, like its name and version.
19
+ */
20
+ constructor(ai, options) {
21
+ this.ai = ai;
22
+ this.options = options;
23
+ }
24
+ /**
25
+ * Initializes the MCP server instance and registers request handlers. It
26
+ * dynamically imports MCP SDK components and sets up handlers for listing
27
+ * tools, calling tools, listing prompts, and getting prompts. It also
28
+ * resolves and stores all tool and prompt actions from the Genkit instance.
29
+ *
30
+ * This method is called by the constructor and ensures the server is ready
31
+ * before any requests are handled. It's idempotent.
32
+ */
33
+ async setup() {
34
+ if (this.actionsResolved) return;
35
+ const { Server } = await import("@modelcontextprotocol/sdk/server/index.js");
36
+ this.server = new Server(
37
+ { name: this.options.name, version: this.options.version || "1.0.0" },
38
+ {
39
+ capabilities: {
40
+ prompts: {},
41
+ tools: {}
42
+ }
43
+ }
44
+ );
45
+ const {
46
+ CallToolRequestSchema,
47
+ GetPromptRequestSchema,
48
+ ListPromptsRequestSchema,
49
+ ListToolsRequestSchema
50
+ } = await import("@modelcontextprotocol/sdk/types.js");
51
+ this.server.setRequestHandler(
52
+ ListToolsRequestSchema,
53
+ this.listTools.bind(this)
54
+ );
55
+ this.server.setRequestHandler(
56
+ CallToolRequestSchema,
57
+ this.callTool.bind(this)
58
+ );
59
+ this.server.setRequestHandler(
60
+ ListPromptsRequestSchema,
61
+ this.listPrompts.bind(this)
62
+ );
63
+ this.server.setRequestHandler(
64
+ GetPromptRequestSchema,
65
+ this.getPrompt.bind(this)
66
+ );
67
+ const allActions = await this.ai.registry.listActions();
68
+ const toolList = [];
69
+ const promptList = [];
70
+ for (const k in allActions) {
71
+ if (k.startsWith("/tool/")) {
72
+ toolList.push(allActions[k]);
73
+ } else if (k.startsWith("/prompt/")) {
74
+ promptList.push(allActions[k]);
75
+ }
76
+ }
77
+ this.toolActions = toolList;
78
+ this.promptActions = promptList;
79
+ this.actionsResolved = true;
80
+ }
81
+ /**
82
+ * Handles MCP requests to list available tools.
83
+ * It maps the resolved Genkit tool actions to the MCP Tool format.
84
+ * @param req The MCP ListToolsRequest.
85
+ * @returns A Promise resolving to an MCP ListToolsResult.
86
+ */
87
+ async listTools(req) {
88
+ await this.setup();
89
+ return {
90
+ tools: this.toolActions.map((t) => {
91
+ const def = toToolDefinition(t);
92
+ return {
93
+ name: def.name,
94
+ inputSchema: def.inputSchema || { type: "object" },
95
+ description: def.description,
96
+ _meta: t.__action.metadata?.mcp?._meta
97
+ };
98
+ })
99
+ };
100
+ }
101
+ /**
102
+ * Handles MCP requests to call a specific tool. It finds the corresponding
103
+ * Genkit tool action and executes it with the provided arguments. The result
104
+ * is then formatted as an MCP CallToolResult.
105
+ * @param req The MCP CallToolRequest containing the tool name and arguments.
106
+ * @returns A Promise resolving to an MCP CallToolResult.
107
+ * @throws GenkitError if the requested tool is not found.
108
+ */
109
+ async callTool(req) {
110
+ await this.setup();
111
+ const tool = this.toolActions.find(
112
+ (t) => t.__action.name === req.params.name
113
+ );
114
+ if (!tool)
115
+ throw new GenkitError({
116
+ status: "NOT_FOUND",
117
+ message: `Tried to call tool '${req.params.name}' but it could not be found.`
118
+ });
119
+ const result = await tool(req.params.arguments);
120
+ return {
121
+ content: [
122
+ {
123
+ type: "text",
124
+ text: typeof result === "string" ? result : JSON.stringify(result)
125
+ }
126
+ ]
127
+ };
128
+ }
129
+ /**
130
+ * Handles MCP requests to list available prompts.
131
+ * It maps the resolved Genkit prompt actions to the MCP Prompt format,
132
+ * including converting input schemas to MCP argument definitions.
133
+ * @param req The MCP ListPromptsRequest.
134
+ * @returns A Promise resolving to an MCP ListPromptsResult.
135
+ */
136
+ async listPrompts(req) {
137
+ await this.setup();
138
+ return {
139
+ prompts: this.promptActions.map((p) => {
140
+ return {
141
+ name: p.__action.name,
142
+ description: p.__action.description,
143
+ arguments: toMcpPromptArguments(p),
144
+ _meta: p.__action.metadata?.mcp?._meta
145
+ };
146
+ })
147
+ };
148
+ }
149
+ /**
150
+ * Handles MCP requests to get (render) a specific prompt. It finds the
151
+ * corresponding Genkit prompt action, executes it with the provided
152
+ * arguments, and then formats the resulting messages into the MCP
153
+ * PromptMessage format.
154
+ * @param req The MCP GetPromptRequest containing the prompt name and
155
+ * arguments.
156
+ * @returns A Promise resolving to an MCP GetPromptResult.
157
+ * @throws GenkitError if the requested prompt is not found.
158
+ */
159
+ async getPrompt(req) {
160
+ await this.setup();
161
+ const prompt = this.promptActions.find(
162
+ (p) => p.__action.name === req.params.name
163
+ );
164
+ if (!prompt)
165
+ throw new GenkitError({
166
+ status: "NOT_FOUND",
167
+ message: `[MCP Server] Tried to call prompt '${req.params.name}' but it could not be found.`
168
+ });
169
+ const result = await prompt(req.params.arguments);
170
+ return {
171
+ description: prompt.__action.description,
172
+ messages: result.messages.map(toMcpPromptMessage)
173
+ };
174
+ }
175
+ /**
176
+ * Starts the MCP server with the specified transport or a default
177
+ * StdioServerTransport. Ensures the server is set up before connecting the
178
+ * transport.
179
+ * @param transport Optional MCP transport instance. If not provided, a
180
+ * StdioServerTransport will be created and used.
181
+ */
182
+ async start(transport) {
183
+ if (!transport) {
184
+ const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
185
+ transport = new StdioServerTransport();
186
+ }
187
+ await this.setup();
188
+ await this.server.connect(transport);
189
+ logger.info(
190
+ `[MCP Server] MCP server '${this.options.name}' started successfully.`
191
+ );
192
+ }
193
+ }
194
+ function toMcpPromptArguments(p) {
195
+ const jsonSchema = toJsonSchema({
196
+ schema: p.__action.inputSchema,
197
+ jsonSchema: p.__action.inputJsonSchema
198
+ });
199
+ if (!jsonSchema) return void 0;
200
+ if (!jsonSchema.properties)
201
+ throw new GenkitError({
202
+ status: "FAILED_PRECONDITION",
203
+ message: "[MCP Server] MCP prompts must take objects as input schema."
204
+ });
205
+ const args = [];
206
+ for (const k in jsonSchema.properties) {
207
+ const { type, description } = jsonSchema.properties[k];
208
+ if (type !== "string" && (!Array.isArray(type) || !type.includes("string"))) {
209
+ throw new GenkitError({
210
+ status: "FAILED_PRECONDITION",
211
+ message: `[MCP Server] MCP prompts may only take string arguments, but ${p.__action.name} has property '${k}' of type '${type}'.`
212
+ });
213
+ }
214
+ args.push({
215
+ name: k,
216
+ description,
217
+ required: jsonSchema.required?.includes(k)
218
+ });
219
+ }
220
+ return args;
221
+ }
222
+ const ROLE_MAP = { model: "assistant", user: "user" };
223
+ function toMcpPromptMessage(messageData) {
224
+ if (messageData.role !== "model" && messageData.role !== "user") {
225
+ throw new GenkitError({
226
+ status: "UNIMPLEMENTED",
227
+ message: `[MCP Server] MCP prompt messages do not support role '${messageData.role}'. Only 'user' and 'model' messages are supported.`
228
+ });
229
+ }
230
+ const message = new Message(messageData);
231
+ const common = { role: ROLE_MAP[messageData.role] };
232
+ if (message.media) {
233
+ const { url, contentType } = message.media;
234
+ if (!url.startsWith("data:"))
235
+ throw new GenkitError({
236
+ status: "UNIMPLEMENTED",
237
+ message: `[MCP Server] MCP prompt messages only support base64 data images.`
238
+ });
239
+ const mimeType = contentType || url.substring(url.indexOf(":") + 1, url.indexOf(";"));
240
+ const data = url.substring(url.indexOf(",") + 1);
241
+ return { ...common, content: { type: "image", mimeType, data } };
242
+ } else {
243
+ return { ...common, content: { type: "text", text: message.text } };
244
+ }
245
+ }
246
+ export {
247
+ GenkitMcpServer
248
+ };
249
+ //# sourceMappingURL=server.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n GenkitError,\n Message,\n type Genkit,\n type MessageData,\n type PromptAction,\n} from 'genkit';\nimport type { McpServerOptions } from './index.js';\n\nimport type { Server } from '@modelcontextprotocol/sdk/server/index.js' with { 'resolution-mode': 'import' };\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js' with { 'resolution-mode': 'import' };\nimport type {\n CallToolRequest,\n CallToolResult,\n GetPromptRequest,\n GetPromptResult,\n ListPromptsRequest,\n ListPromptsResult,\n ListToolsRequest,\n ListToolsResult,\n Prompt,\n PromptMessage,\n Tool,\n} from '@modelcontextprotocol/sdk/types.js' with { 'resolution-mode': 'import' };\nimport { logger } from 'genkit/logging';\nimport { toJsonSchema } from 'genkit/schema';\nimport { ToolAction, toToolDefinition } from 'genkit/tool';\n\n/**\n * Represents an MCP (Model Context Protocol) server that exposes Genkit tools\n * and prompts. This class wraps a Genkit instance and makes its registered\n * actions (tools, prompts) available to MCP clients. It handles the translation\n * between Genkit's action definitions and MCP's expected formats.\n */\nexport class GenkitMcpServer {\n ai: Genkit;\n options: McpServerOptions;\n server?: Server;\n actionsResolved = false;\n toolActions: ToolAction[] = [];\n promptActions: PromptAction[] = [];\n\n /**\n * Creates an instance of GenkitMcpServer.\n * @param ai The Genkit instance whose actions will be exposed.\n * @param options Configuration options for the MCP server, like its name and version.\n */\n constructor(ai: Genkit, options: McpServerOptions) {\n this.ai = ai;\n this.options = options;\n }\n\n /**\n * Initializes the MCP server instance and registers request handlers. It\n * dynamically imports MCP SDK components and sets up handlers for listing\n * tools, calling tools, listing prompts, and getting prompts. It also\n * resolves and stores all tool and prompt actions from the Genkit instance.\n *\n * This method is called by the constructor and ensures the server is ready\n * before any requests are handled. It's idempotent.\n */\n async setup(): Promise<void> {\n if (this.actionsResolved) return;\n const { Server } = await import(\n '@modelcontextprotocol/sdk/server/index.js'\n );\n\n this.server = new Server(\n { name: this.options.name, version: this.options.version || '1.0.0' },\n {\n capabilities: {\n prompts: {},\n tools: {},\n },\n }\n );\n\n const {\n CallToolRequestSchema,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListToolsRequestSchema,\n } = await import('@modelcontextprotocol/sdk/types.js');\n\n this.server.setRequestHandler(\n ListToolsRequestSchema,\n this.listTools.bind(this)\n );\n this.server.setRequestHandler(\n CallToolRequestSchema,\n this.callTool.bind(this)\n );\n this.server.setRequestHandler(\n ListPromptsRequestSchema,\n this.listPrompts.bind(this)\n );\n this.server.setRequestHandler(\n GetPromptRequestSchema,\n this.getPrompt.bind(this)\n );\n\n // TODO -- use listResolvableActions.\n const allActions = await this.ai.registry.listActions();\n const toolList: ToolAction[] = [];\n const promptList: PromptAction[] = [];\n for (const k in allActions) {\n if (k.startsWith('/tool/')) {\n toolList.push(allActions[k] as ToolAction);\n } else if (k.startsWith('/prompt/')) {\n promptList.push(allActions[k] as PromptAction);\n }\n }\n this.toolActions = toolList;\n this.promptActions = promptList;\n this.actionsResolved = true;\n }\n\n /**\n * Handles MCP requests to list available tools.\n * It maps the resolved Genkit tool actions to the MCP Tool format.\n * @param req The MCP ListToolsRequest.\n * @returns A Promise resolving to an MCP ListToolsResult.\n */\n async listTools(req: ListToolsRequest): Promise<ListToolsResult> {\n await this.setup();\n return {\n tools: this.toolActions.map((t): Tool => {\n const def = toToolDefinition(t);\n return {\n name: def.name,\n inputSchema: (def.inputSchema as any) || { type: 'object' },\n description: def.description,\n _meta: t.__action.metadata?.mcp?._meta,\n };\n }),\n };\n }\n\n /**\n * Handles MCP requests to call a specific tool. It finds the corresponding\n * Genkit tool action and executes it with the provided arguments. The result\n * is then formatted as an MCP CallToolResult.\n * @param req The MCP CallToolRequest containing the tool name and arguments.\n * @returns A Promise resolving to an MCP CallToolResult.\n * @throws GenkitError if the requested tool is not found.\n */\n async callTool(req: CallToolRequest): Promise<CallToolResult> {\n await this.setup();\n const tool = this.toolActions.find(\n (t) => t.__action.name === req.params.name\n );\n if (!tool)\n throw new GenkitError({\n status: 'NOT_FOUND',\n message: `Tried to call tool '${req.params.name}' but it could not be found.`,\n });\n const result = await tool(req.params.arguments);\n return {\n content: [\n {\n type: 'text',\n text: typeof result === 'string' ? result : JSON.stringify(result),\n },\n ],\n };\n }\n\n /**\n * Handles MCP requests to list available prompts.\n * It maps the resolved Genkit prompt actions to the MCP Prompt format,\n * including converting input schemas to MCP argument definitions.\n * @param req The MCP ListPromptsRequest.\n * @returns A Promise resolving to an MCP ListPromptsResult.\n */\n async listPrompts(req: ListPromptsRequest): Promise<ListPromptsResult> {\n await this.setup();\n return {\n prompts: this.promptActions.map((p): Prompt => {\n return {\n name: p.__action.name,\n description: p.__action.description,\n arguments: toMcpPromptArguments(p),\n _meta: p.__action.metadata?.mcp?._meta,\n };\n }),\n };\n }\n\n /**\n * Handles MCP requests to get (render) a specific prompt. It finds the\n * corresponding Genkit prompt action, executes it with the provided\n * arguments, and then formats the resulting messages into the MCP\n * PromptMessage format.\n * @param req The MCP GetPromptRequest containing the prompt name and\n * arguments.\n * @returns A Promise resolving to an MCP GetPromptResult.\n * @throws GenkitError if the requested prompt is not found.\n */\n async getPrompt(req: GetPromptRequest): Promise<GetPromptResult> {\n await this.setup();\n const prompt = this.promptActions.find(\n (p) => p.__action.name === req.params.name\n );\n if (!prompt)\n throw new GenkitError({\n status: 'NOT_FOUND',\n message: `[MCP Server] Tried to call prompt '${req.params.name}' but it could not be found.`,\n });\n const result = await prompt(req.params.arguments);\n return {\n description: prompt.__action.description,\n messages: result.messages.map(toMcpPromptMessage),\n };\n }\n\n /**\n * Starts the MCP server with the specified transport or a default\n * StdioServerTransport. Ensures the server is set up before connecting the\n * transport.\n * @param transport Optional MCP transport instance. If not provided, a\n * StdioServerTransport will be created and used.\n */\n async start(transport?: Transport) {\n if (!transport) {\n const { StdioServerTransport } = await import(\n '@modelcontextprotocol/sdk/server/stdio.js'\n );\n transport = new StdioServerTransport();\n }\n await this.setup();\n await this.server!.connect(transport);\n logger.info(\n `[MCP Server] MCP server '${this.options.name}' started successfully.`\n );\n }\n}\n\n/**\n * Converts a Genkit prompt's input schema to an array of MCP prompt arguments.\n * MCP prompts currently only support string arguments.\n * @param p The Genkit PromptAction.\n * @returns An array of MCP prompt arguments, or undefined if the schema is not defined.\n * @throws GenkitError if the input schema is not an object or if any property is not a string.\n */\nfunction toMcpPromptArguments(\n p: PromptAction\n): Prompt['arguments'] | undefined {\n const jsonSchema = toJsonSchema({\n schema: p.__action.inputSchema,\n jsonSchema: p.__action.inputJsonSchema,\n });\n\n if (!jsonSchema) return undefined;\n if (!jsonSchema.properties)\n throw new GenkitError({\n status: 'FAILED_PRECONDITION',\n message: '[MCP Server] MCP prompts must take objects as input schema.',\n });\n\n const args: Prompt['arguments'] = [];\n for (const k in jsonSchema.properties) {\n const { type, description } = jsonSchema.properties[k];\n if (\n type !== 'string' &&\n (!Array.isArray(type) || !type.includes('string'))\n ) {\n throw new GenkitError({\n status: 'FAILED_PRECONDITION',\n message: `[MCP Server] MCP prompts may only take string arguments, but ${p.__action.name} has property '${k}' of type '${type}'.`,\n });\n }\n args.push({\n name: k,\n description,\n required: jsonSchema.required?.includes(k),\n });\n }\n return args;\n}\n\nconst ROLE_MAP = { model: 'assistant', user: 'user' } as const;\n\n/**\n * Converts a Genkit MessageData object to an MCP PromptMessage.\n * Handles mapping of roles and content types (text, image).\n * MCP only supports 'user' and 'assistant' (model) roles and base64 data images.\n * @param messageData The Genkit MessageData object.\n * @returns An MCP PromptMessage.\n * @throws GenkitError if the role is unsupported or if media is not a data URL.\n */\nfunction toMcpPromptMessage(messageData: MessageData): PromptMessage {\n if (messageData.role !== 'model' && messageData.role !== 'user') {\n throw new GenkitError({\n status: 'UNIMPLEMENTED',\n message: `[MCP Server] MCP prompt messages do not support role '${messageData.role}'. Only 'user' and 'model' messages are supported.`,\n });\n }\n const message = new Message(messageData);\n const common = { role: ROLE_MAP[messageData.role] };\n if (message.media) {\n const { url, contentType } = message.media;\n if (!url.startsWith('data:'))\n throw new GenkitError({\n status: 'UNIMPLEMENTED',\n message: `[MCP Server] MCP prompt messages only support base64 data images.`,\n });\n const mimeType =\n contentType || url.substring(url.indexOf(':')! + 1, url.indexOf(';'));\n const data = url.substring(url.indexOf(',') + 1);\n return { ...common, content: { type: 'image', mimeType, data } };\n } else {\n return { ...common, content: { type: 'text', text: message.text } };\n }\n}\n"],"mappings":"AAgBA;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AAkBP,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAqB,wBAAwB;AAQtC,MAAM,gBAAgB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA,kBAAkB;AAAA,EAClB,cAA4B,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EACpE;AACF;","names":[]}
@@ -0,0 +1,11 @@
1
+ export { fromMcpPart, fromMcpPromptMessage } from './message.mjs';
2
+ export { fetchAllPrompts, getExecutablePrompt, registerAllPrompts } from './prompts.mjs';
3
+ export { fetchDynamicTools, registerAllTools } from './tools.mjs';
4
+ export { transportFrom } from './transport.mjs';
5
+ import '@modelcontextprotocol/sdk/types.js';
6
+ import 'genkit';
7
+ import '@modelcontextprotocol/sdk/client/index.js';
8
+ import '../client/client.mjs';
9
+ import '@modelcontextprotocol/sdk/client/stdio.js';
10
+ import '@modelcontextprotocol/sdk/client/streamableHttp.js';
11
+ import '@modelcontextprotocol/sdk/shared/transport.js';
@@ -0,0 +1,11 @@
1
+ export { fromMcpPart, fromMcpPromptMessage } from './message.js';
2
+ export { fetchAllPrompts, getExecutablePrompt, registerAllPrompts } from './prompts.js';
3
+ export { fetchDynamicTools, registerAllTools } from './tools.js';
4
+ export { transportFrom } from './transport.js';
5
+ import '@modelcontextprotocol/sdk/types.js';
6
+ import 'genkit';
7
+ import '@modelcontextprotocol/sdk/client/index.js';
8
+ import '../client/client.js';
9
+ import '@modelcontextprotocol/sdk/client/stdio.js';
10
+ import '@modelcontextprotocol/sdk/client/streamableHttp.js';
11
+ import '@modelcontextprotocol/sdk/shared/transport.js';
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
+ var util_exports = {};
17
+ module.exports = __toCommonJS(util_exports);
18
+ __reExport(util_exports, require("./message.js"), module.exports);
19
+ __reExport(util_exports, require("./prompts.js"), module.exports);
20
+ __reExport(util_exports, require("./tools.js"), module.exports);
21
+ __reExport(util_exports, require("./transport.js"), module.exports);
22
+ // Annotate the CommonJS export names for ESM import in node:
23
+ 0 && (module.exports = {
24
+ ...require("./message.js"),
25
+ ...require("./prompts.js"),
26
+ ...require("./tools.js"),
27
+ ...require("./transport.js")
28
+ });
29
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/util/index.ts"],"sourcesContent":["/**\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './message.js';\nexport * from './prompts.js';\nexport * from './tools.js';\nexport * from './transport.js';\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAAA;AAgBA,yBAAc,yBAhBd;AAiBA,yBAAc,yBAjBd;AAkBA,yBAAc,uBAlBd;AAmBA,yBAAc,2BAnBd;","names":[]}
@@ -0,0 +1,5 @@
1
+ export * from "./message.js";
2
+ export * from "./prompts.js";
3
+ export * from "./tools.js";
4
+ export * from "./transport.js";
5
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/util/index.ts"],"sourcesContent":["/**\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './message.js';\nexport * from './prompts.js';\nexport * from './tools.js';\nexport * from './transport.js';\n"],"mappings":"AAgBA,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;","names":[]}
@@ -0,0 +1,43 @@
1
+ import { PromptMessage } from '@modelcontextprotocol/sdk/types.js';
2
+ import { MessageData, Part } from 'genkit';
3
+
4
+ /**
5
+ * Copyright 2024 Google LLC
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ /**
21
+ * Converts an MCP (Model Context Protocol) PromptMessage into Genkit's
22
+ * MessageData format. This involves mapping MCP roles (user, assistant) to
23
+ * Genkit roles (user, model) and transforming the MCP content part into a
24
+ * Genkit Part.
25
+ *
26
+ * @param message The MCP PromptMessage to convert.
27
+ * @returns The corresponding Genkit MessageData object.
28
+ */
29
+ declare function fromMcpPromptMessage(message: PromptMessage): MessageData;
30
+ /**
31
+ * Converts an MCP message content part (text, image, or resource) into a Genkit
32
+ * Part.
33
+ * - Text parts are directly mapped.
34
+ * - Image parts are converted to Genkit media parts with a data URL.
35
+ * - Resource parts currently result in an empty Genkit Part (further
36
+ * implementation may be needed).
37
+ *
38
+ * @param part The MCP PromptMessage content part to convert.
39
+ * @returns The corresponding Genkit Part.
40
+ */
41
+ declare function fromMcpPart(part: PromptMessage['content']): Part;
42
+
43
+ export { fromMcpPart, fromMcpPromptMessage };
@@ -0,0 +1,43 @@
1
+ import { PromptMessage } from '@modelcontextprotocol/sdk/types.js';
2
+ import { MessageData, Part } from 'genkit';
3
+
4
+ /**
5
+ * Copyright 2024 Google LLC
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ /**
21
+ * Converts an MCP (Model Context Protocol) PromptMessage into Genkit's
22
+ * MessageData format. This involves mapping MCP roles (user, assistant) to
23
+ * Genkit roles (user, model) and transforming the MCP content part into a
24
+ * Genkit Part.
25
+ *
26
+ * @param message The MCP PromptMessage to convert.
27
+ * @returns The corresponding Genkit MessageData object.
28
+ */
29
+ declare function fromMcpPromptMessage(message: PromptMessage): MessageData;
30
+ /**
31
+ * Converts an MCP message content part (text, image, or resource) into a Genkit
32
+ * Part.
33
+ * - Text parts are directly mapped.
34
+ * - Image parts are converted to Genkit media parts with a data URL.
35
+ * - Resource parts currently result in an empty Genkit Part (further
36
+ * implementation may be needed).
37
+ *
38
+ * @param part The MCP PromptMessage content part to convert.
39
+ * @returns The corresponding Genkit Part.
40
+ */
41
+ declare function fromMcpPart(part: PromptMessage['content']): Part;
42
+
43
+ export { fromMcpPart, fromMcpPromptMessage };
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var message_exports = {};
20
+ __export(message_exports, {
21
+ fromMcpPart: () => fromMcpPart,
22
+ fromMcpPromptMessage: () => fromMcpPromptMessage
23
+ });
24
+ module.exports = __toCommonJS(message_exports);
25
+ const ROLE_MAP = {
26
+ user: "user",
27
+ assistant: "model"
28
+ };
29
+ function fromMcpPromptMessage(message) {
30
+ return {
31
+ role: ROLE_MAP[message.role],
32
+ content: [fromMcpPart(message.content)]
33
+ };
34
+ }
35
+ function fromMcpPart(part) {
36
+ switch (part.type) {
37
+ case "text":
38
+ return { text: part.text };
39
+ case "image":
40
+ return {
41
+ media: {
42
+ contentType: part.mimeType,
43
+ url: `data:${part.mimeType};base64,${part.data}`
44
+ }
45
+ };
46
+ case "resource":
47
+ return {
48
+ resource: {
49
+ uri: part.uri
50
+ }
51
+ };
52
+ default:
53
+ return {};
54
+ }
55
+ }
56
+ // Annotate the CommonJS export names for ESM import in node:
57
+ 0 && (module.exports = {
58
+ fromMcpPart,
59
+ fromMcpPromptMessage
60
+ });
61
+ //# sourceMappingURL=message.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/util/message.ts"],"sourcesContent":["/**\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PromptMessage } from '@modelcontextprotocol/sdk/types.js' with { 'resolution-mode': 'import' };\nimport { type MessageData, type Part } from 'genkit';\n\nconst ROLE_MAP = {\n user: 'user',\n assistant: 'model',\n} as const;\n\n/**\n * Converts an MCP (Model Context Protocol) PromptMessage into Genkit's\n * MessageData format. This involves mapping MCP roles (user, assistant) to\n * Genkit roles (user, model) and transforming the MCP content part into a\n * Genkit Part.\n *\n * @param message The MCP PromptMessage to convert.\n * @returns The corresponding Genkit MessageData object.\n */\nexport function fromMcpPromptMessage(message: PromptMessage): MessageData {\n return {\n role: ROLE_MAP[message.role],\n content: [fromMcpPart(message.content)],\n };\n}\n\n/**\n * Converts an MCP message content part (text, image, or resource) into a Genkit\n * Part.\n * - Text parts are directly mapped.\n * - Image parts are converted to Genkit media parts with a data URL.\n * - Resource parts currently result in an empty Genkit Part (further\n * implementation may be needed).\n *\n * @param part The MCP PromptMessage content part to convert.\n * @returns The corresponding Genkit Part.\n */\nexport function fromMcpPart(part: PromptMessage['content']): Part {\n switch (part.type) {\n case 'text':\n return { text: part.text };\n case 'image':\n return {\n media: {\n contentType: part.mimeType,\n url: `data:${part.mimeType};base64,${part.data}`,\n },\n };\n case 'resource':\n return {\n resource: {\n uri: part.uri as string,\n },\n };\n default:\n return {};\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmBA,MAAM,WAAW;AAAA,EACf,MAAM;AAAA,EACN,WAAW;AACb;AAWO,SAAS,qBAAqB,SAAqC;AACxE,SAAO;AAAA,IACL,MAAM,SAAS,QAAQ,IAAI;AAAA,IAC3B,SAAS,CAAC,YAAY,QAAQ,OAAO,CAAC;AAAA,EACxC;AACF;AAaO,SAAS,YAAY,MAAsC;AAChE,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,aAAO,EAAE,MAAM,KAAK,KAAK;AAAA,IAC3B,KAAK;AACH,aAAO;AAAA,QACL,OAAO;AAAA,UACL,aAAa,KAAK;AAAA,UAClB,KAAK,QAAQ,KAAK,QAAQ,WAAW,KAAK,IAAI;AAAA,QAChD;AAAA,MACF;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,UAAU;AAAA,UACR,KAAK,KAAK;AAAA,QACZ;AAAA,MACF;AAAA,IACF;AACE,aAAO,CAAC;AAAA,EACZ;AACF;","names":[]}
@@ -0,0 +1,36 @@
1
+ const ROLE_MAP = {
2
+ user: "user",
3
+ assistant: "model"
4
+ };
5
+ function fromMcpPromptMessage(message) {
6
+ return {
7
+ role: ROLE_MAP[message.role],
8
+ content: [fromMcpPart(message.content)]
9
+ };
10
+ }
11
+ function fromMcpPart(part) {
12
+ switch (part.type) {
13
+ case "text":
14
+ return { text: part.text };
15
+ case "image":
16
+ return {
17
+ media: {
18
+ contentType: part.mimeType,
19
+ url: `data:${part.mimeType};base64,${part.data}`
20
+ }
21
+ };
22
+ case "resource":
23
+ return {
24
+ resource: {
25
+ uri: part.uri
26
+ }
27
+ };
28
+ default:
29
+ return {};
30
+ }
31
+ }
32
+ export {
33
+ fromMcpPart,
34
+ fromMcpPromptMessage
35
+ };
36
+ //# sourceMappingURL=message.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/util/message.ts"],"sourcesContent":["/**\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PromptMessage } from '@modelcontextprotocol/sdk/types.js' with { 'resolution-mode': 'import' };\nimport { type MessageData, type Part } from 'genkit';\n\nconst ROLE_MAP = {\n user: 'user',\n assistant: 'model',\n} as const;\n\n/**\n * Converts an MCP (Model Context Protocol) PromptMessage into Genkit's\n * MessageData format. This involves mapping MCP roles (user, assistant) to\n * Genkit roles (user, model) and transforming the MCP content part into a\n * Genkit Part.\n *\n * @param message The MCP PromptMessage to convert.\n * @returns The corresponding Genkit MessageData object.\n */\nexport function fromMcpPromptMessage(message: PromptMessage): MessageData {\n return {\n role: ROLE_MAP[message.role],\n content: [fromMcpPart(message.content)],\n };\n}\n\n/**\n * Converts an MCP message content part (text, image, or resource) into a Genkit\n * Part.\n * - Text parts are directly mapped.\n * - Image parts are converted to Genkit media parts with a data URL.\n * - Resource parts currently result in an empty Genkit Part (further\n * implementation may be needed).\n *\n * @param part The MCP PromptMessage content part to convert.\n * @returns The corresponding Genkit Part.\n */\nexport function fromMcpPart(part: PromptMessage['content']): Part {\n switch (part.type) {\n case 'text':\n return { text: part.text };\n case 'image':\n return {\n media: {\n contentType: part.mimeType,\n url: `data:${part.mimeType};base64,${part.data}`,\n },\n };\n case 'resource':\n return {\n resource: {\n uri: part.uri as string,\n },\n };\n default:\n return {};\n }\n}\n"],"mappings":"AAmBA,MAAM,WAAW;AAAA,EACf,MAAM;AAAA,EACN,WAAW;AACb;AAWO,SAAS,qBAAqB,SAAqC;AACxE,SAAO;AAAA,IACL,MAAM,SAAS,QAAQ,IAAI;AAAA,IAC3B,SAAS,CAAC,YAAY,QAAQ,OAAO,CAAC;AAAA,EACxC;AACF;AAaO,SAAS,YAAY,MAAsC;AAChE,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,aAAO,EAAE,MAAM,KAAK,KAAK;AAAA,IAC3B,KAAK;AACH,aAAO;AAAA,QACL,OAAO;AAAA,UACL,aAAa,KAAK;AAAA,UAClB,KAAK,QAAQ,KAAK,QAAQ,WAAW,KAAK,IAAI;AAAA,QAChD;AAAA,MACF;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,UAAU;AAAA,UACR,KAAK,KAAK;AAAA,QACZ;AAAA,MACF;AAAA,IACF;AACE,aAAO,CAAC;AAAA,EACZ;AACF;","names":[]}
@@ -0,0 +1,45 @@
1
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
2
+ import { Genkit, PromptGenerateOptions, ExecutablePrompt } from 'genkit';
3
+
4
+ /**
5
+ * Copyright 2024 Google LLC
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ /**
21
+ * Lookup all prompts available in the server and register each as a Genkit
22
+ * prompt.
23
+ */
24
+ declare function registerAllPrompts(ai: Genkit, client: Client, params: {
25
+ name: string;
26
+ serverName: string;
27
+ }): Promise<void>;
28
+ /**
29
+ * Lookup a specified prompt from the server and return as an ExecutablePrompt.
30
+ */
31
+ declare function getExecutablePrompt(client: Client, params: {
32
+ name: string;
33
+ serverName: string;
34
+ promptName: string;
35
+ ai: Genkit;
36
+ options?: PromptGenerateOptions;
37
+ }): Promise<ExecutablePrompt | undefined>;
38
+ declare function fetchAllPrompts(client: Client, params: {
39
+ name: string;
40
+ serverName: string;
41
+ ai: Genkit;
42
+ options?: PromptGenerateOptions;
43
+ }): Promise<ExecutablePrompt[]>;
44
+
45
+ export { fetchAllPrompts, getExecutablePrompt, registerAllPrompts };