@inkeep/agents-run-api 0.1.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 (149) hide show
  1. package/README.md +117 -0
  2. package/dist/AgentExecutionServer.d.ts +23 -0
  3. package/dist/AgentExecutionServer.d.ts.map +1 -0
  4. package/dist/AgentExecutionServer.js +32 -0
  5. package/dist/__tests__/setup.d.ts +4 -0
  6. package/dist/__tests__/setup.d.ts.map +1 -0
  7. package/dist/__tests__/setup.js +50 -0
  8. package/dist/__tests__/utils/testProject.d.ts +18 -0
  9. package/dist/__tests__/utils/testProject.d.ts.map +1 -0
  10. package/dist/__tests__/utils/testProject.js +26 -0
  11. package/dist/__tests__/utils/testRequest.d.ts +8 -0
  12. package/dist/__tests__/utils/testRequest.d.ts.map +1 -0
  13. package/dist/__tests__/utils/testRequest.js +32 -0
  14. package/dist/__tests__/utils/testTenant.d.ts +64 -0
  15. package/dist/__tests__/utils/testTenant.d.ts.map +1 -0
  16. package/dist/__tests__/utils/testTenant.js +71 -0
  17. package/dist/a2a/client.d.ts +182 -0
  18. package/dist/a2a/client.d.ts.map +1 -0
  19. package/dist/a2a/client.js +645 -0
  20. package/dist/a2a/handlers.d.ts +4 -0
  21. package/dist/a2a/handlers.d.ts.map +1 -0
  22. package/dist/a2a/handlers.js +657 -0
  23. package/dist/a2a/transfer.d.ts +18 -0
  24. package/dist/a2a/transfer.d.ts.map +1 -0
  25. package/dist/a2a/transfer.js +22 -0
  26. package/dist/a2a/types.d.ts +63 -0
  27. package/dist/a2a/types.d.ts.map +1 -0
  28. package/dist/a2a/types.js +1 -0
  29. package/dist/agents/Agent.d.ts +154 -0
  30. package/dist/agents/Agent.d.ts.map +1 -0
  31. package/dist/agents/Agent.js +1105 -0
  32. package/dist/agents/ModelFactory.d.ts +62 -0
  33. package/dist/agents/ModelFactory.d.ts.map +1 -0
  34. package/dist/agents/ModelFactory.js +208 -0
  35. package/dist/agents/SystemPromptBuilder.d.ts +14 -0
  36. package/dist/agents/SystemPromptBuilder.d.ts.map +1 -0
  37. package/dist/agents/SystemPromptBuilder.js +62 -0
  38. package/dist/agents/ToolSessionManager.d.ts +61 -0
  39. package/dist/agents/ToolSessionManager.d.ts.map +1 -0
  40. package/dist/agents/ToolSessionManager.js +143 -0
  41. package/dist/agents/artifactTools.d.ts +30 -0
  42. package/dist/agents/artifactTools.d.ts.map +1 -0
  43. package/dist/agents/artifactTools.js +463 -0
  44. package/dist/agents/generateTaskHandler.d.ts +41 -0
  45. package/dist/agents/generateTaskHandler.d.ts.map +1 -0
  46. package/dist/agents/generateTaskHandler.js +350 -0
  47. package/dist/agents/relationTools.d.ts +33 -0
  48. package/dist/agents/relationTools.d.ts.map +1 -0
  49. package/dist/agents/relationTools.js +245 -0
  50. package/dist/agents/types.d.ts +23 -0
  51. package/dist/agents/types.d.ts.map +1 -0
  52. package/dist/agents/types.js +1 -0
  53. package/dist/agents/versions/V1Config.d.ts +21 -0
  54. package/dist/agents/versions/V1Config.d.ts.map +1 -0
  55. package/dist/agents/versions/V1Config.js +285 -0
  56. package/dist/app.d.ts +4 -0
  57. package/dist/app.d.ts.map +1 -0
  58. package/dist/app.js +194 -0
  59. package/dist/data/agentGraph.d.ts +4 -0
  60. package/dist/data/agentGraph.d.ts.map +1 -0
  61. package/dist/data/agentGraph.js +73 -0
  62. package/dist/data/agents.d.ts +4 -0
  63. package/dist/data/agents.d.ts.map +1 -0
  64. package/dist/data/agents.js +73 -0
  65. package/dist/data/conversations.d.ts +59 -0
  66. package/dist/data/conversations.d.ts.map +1 -0
  67. package/dist/data/conversations.js +216 -0
  68. package/dist/data/db/clean.d.ts +6 -0
  69. package/dist/data/db/clean.d.ts.map +1 -0
  70. package/dist/data/db/clean.js +77 -0
  71. package/dist/data/db/dbClient.d.ts +3 -0
  72. package/dist/data/db/dbClient.d.ts.map +1 -0
  73. package/dist/data/db/dbClient.js +13 -0
  74. package/dist/env.d.ts +43 -0
  75. package/dist/env.d.ts.map +1 -0
  76. package/dist/env.js +63 -0
  77. package/dist/handlers/executionHandler.d.ts +36 -0
  78. package/dist/handlers/executionHandler.d.ts.map +1 -0
  79. package/dist/handlers/executionHandler.js +402 -0
  80. package/dist/index.d.ts +5 -0
  81. package/dist/index.d.ts.map +1 -0
  82. package/dist/index.js +43 -0
  83. package/dist/instrumentation.d.ts +13 -0
  84. package/dist/instrumentation.d.ts.map +1 -0
  85. package/dist/instrumentation.js +66 -0
  86. package/dist/logger.d.ts +4 -0
  87. package/dist/logger.d.ts.map +1 -0
  88. package/dist/logger.js +32 -0
  89. package/dist/middleware/api-key-auth.d.ts +22 -0
  90. package/dist/middleware/api-key-auth.d.ts.map +1 -0
  91. package/dist/middleware/api-key-auth.js +139 -0
  92. package/dist/middleware/index.d.ts +2 -0
  93. package/dist/middleware/index.d.ts.map +1 -0
  94. package/dist/middleware/index.js +1 -0
  95. package/dist/openapi.d.ts +2 -0
  96. package/dist/openapi.d.ts.map +1 -0
  97. package/dist/openapi.js +36 -0
  98. package/dist/routes/agents.d.ts +4 -0
  99. package/dist/routes/agents.d.ts.map +1 -0
  100. package/dist/routes/agents.js +155 -0
  101. package/dist/routes/chat.d.ts +4 -0
  102. package/dist/routes/chat.d.ts.map +1 -0
  103. package/dist/routes/chat.js +308 -0
  104. package/dist/routes/chatDataStream.d.ts +4 -0
  105. package/dist/routes/chatDataStream.d.ts.map +1 -0
  106. package/dist/routes/chatDataStream.js +179 -0
  107. package/dist/routes/mcp.d.ts +4 -0
  108. package/dist/routes/mcp.d.ts.map +1 -0
  109. package/dist/routes/mcp.js +500 -0
  110. package/dist/tracer.d.ts +24 -0
  111. package/dist/tracer.d.ts.map +1 -0
  112. package/dist/tracer.js +97 -0
  113. package/dist/types/chat.d.ts +25 -0
  114. package/dist/types/chat.d.ts.map +1 -0
  115. package/dist/types/chat.js +1 -0
  116. package/dist/types/execution-context.d.ts +14 -0
  117. package/dist/types/execution-context.d.ts.map +1 -0
  118. package/dist/types/execution-context.js +14 -0
  119. package/dist/utils/agent-operations.d.ts +79 -0
  120. package/dist/utils/agent-operations.d.ts.map +1 -0
  121. package/dist/utils/agent-operations.js +67 -0
  122. package/dist/utils/artifact-component-schema.d.ts +29 -0
  123. package/dist/utils/artifact-component-schema.d.ts.map +1 -0
  124. package/dist/utils/artifact-component-schema.js +119 -0
  125. package/dist/utils/artifact-parser.d.ts +71 -0
  126. package/dist/utils/artifact-parser.d.ts.map +1 -0
  127. package/dist/utils/artifact-parser.js +251 -0
  128. package/dist/utils/cleanup.d.ts +19 -0
  129. package/dist/utils/cleanup.d.ts.map +1 -0
  130. package/dist/utils/cleanup.js +66 -0
  131. package/dist/utils/data-component-schema.d.ts +6 -0
  132. package/dist/utils/data-component-schema.d.ts.map +1 -0
  133. package/dist/utils/data-component-schema.js +43 -0
  134. package/dist/utils/graph-session.d.ts +200 -0
  135. package/dist/utils/graph-session.d.ts.map +1 -0
  136. package/dist/utils/graph-session.js +1009 -0
  137. package/dist/utils/incremental-stream-parser.d.ts +57 -0
  138. package/dist/utils/incremental-stream-parser.d.ts.map +1 -0
  139. package/dist/utils/incremental-stream-parser.js +287 -0
  140. package/dist/utils/response-formatter.d.ts +27 -0
  141. package/dist/utils/response-formatter.d.ts.map +1 -0
  142. package/dist/utils/response-formatter.js +160 -0
  143. package/dist/utils/stream-helpers.d.ts +162 -0
  144. package/dist/utils/stream-helpers.d.ts.map +1 -0
  145. package/dist/utils/stream-helpers.js +385 -0
  146. package/dist/utils/stream-registry.d.ts +18 -0
  147. package/dist/utils/stream-registry.d.ts.map +1 -0
  148. package/dist/utils/stream-registry.js +33 -0
  149. package/package.json +88 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chatDataStream.d.ts","sourceRoot":"","sources":["../../src/routes/chatDataStream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,WAAW,EAAK,MAAM,mBAAmB,CAAC;AAsBhE,QAAA,MAAM,GAAG,0CAAoB,CAAC;AAqM9B,eAAe,GAAG,CAAC"}
@@ -0,0 +1,179 @@
1
+ import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi';
2
+ import { trace } from '@opentelemetry/api';
3
+ import { createUIMessageStream, JsonToSseTransformStream } from 'ai';
4
+ import { stream } from 'hono/streaming';
5
+ import { nanoid } from 'nanoid';
6
+ import { handleContextResolution } from '@inkeep/agents-core';
7
+ import { createMessage, getAgentById, getActiveAgentForConversation, setActiveAgentForConversation, getAgentGraphWithDefaultAgent, contextValidationMiddleware, commonGetErrorResponses, getRequestExecutionContext, } from '@inkeep/agents-core';
8
+ import { ExecutionHandler } from '../handlers/executionHandler.js';
9
+ import { getLogger } from '../logger.js';
10
+ import { createVercelStreamHelper } from '../utils/stream-helpers.js';
11
+ import dbClient from '../data/db/dbClient.js';
12
+ const app = new OpenAPIHono();
13
+ const logger = getLogger('chatDataStream');
14
+ const chatDataStreamRoute = createRoute({
15
+ method: 'post',
16
+ path: '/chat',
17
+ tags: ['chat'],
18
+ summary: 'Chat (Vercel Streaming Protocol)',
19
+ description: 'Chat completion endpoint streaming with Vercel data stream protocol.',
20
+ security: [{ bearerAuth: [] }],
21
+ request: {
22
+ body: {
23
+ content: {
24
+ 'application/json': {
25
+ schema: z.object({
26
+ model: z.string().optional(),
27
+ messages: z.array(z.object({
28
+ role: z.enum(['system', 'user', 'assistant', 'function', 'tool']),
29
+ content: z.any(),
30
+ parts: z
31
+ .array(z.object({
32
+ type: z.union([
33
+ z.enum(['text', 'image', 'audio', 'video', 'file']),
34
+ z.string().regex(/^data-/, 'Type must start with "data-"'),
35
+ ]),
36
+ text: z.string().optional(),
37
+ }))
38
+ .optional(),
39
+ })),
40
+ id: z.string().optional(),
41
+ conversationId: z.string().optional(),
42
+ requestContext: z
43
+ .record(z.string(), z.unknown())
44
+ .optional()
45
+ .describe('Context data for template processing'),
46
+ }),
47
+ },
48
+ },
49
+ },
50
+ },
51
+ responses: {
52
+ 200: {
53
+ description: 'Streamed chat completion',
54
+ headers: z.object({
55
+ 'Content-Type': z.string().default('text/plain; charset=utf-8'),
56
+ 'x-vercel-ai-data-stream': z.string().default('v1'),
57
+ }),
58
+ },
59
+ ...commonGetErrorResponses,
60
+ },
61
+ });
62
+ // Apply context validation middleware
63
+ app.use('/chat', contextValidationMiddleware(dbClient));
64
+ app.openapi(chatDataStreamRoute, async (c) => {
65
+ try {
66
+ // Get execution context from API key authentication
67
+ const executionContext = getRequestExecutionContext(c);
68
+ const { tenantId, projectId, graphId } = executionContext;
69
+ const body = await c.req.valid('json');
70
+ const conversationId = body.conversationId || nanoid();
71
+ // Add conversation ID to parent span
72
+ const activeSpan = trace.getActiveSpan();
73
+ if (activeSpan) {
74
+ activeSpan.setAttributes({
75
+ 'conversation.id': conversationId,
76
+ 'tenant.id': tenantId,
77
+ 'graph.id': graphId,
78
+ 'project.id': projectId,
79
+ });
80
+ }
81
+ const agentGraph = await getAgentGraphWithDefaultAgent(dbClient)({
82
+ scopes: { tenantId, projectId },
83
+ graphId,
84
+ });
85
+ if (!agentGraph) {
86
+ return c.json({ error: 'Agent graph not found' }, 404);
87
+ }
88
+ const defaultAgentId = agentGraph.defaultAgentId;
89
+ const graphName = agentGraph.name;
90
+ const activeAgent = await getActiveAgentForConversation(dbClient)({
91
+ scopes: { tenantId, projectId },
92
+ conversationId,
93
+ });
94
+ if (!activeAgent) {
95
+ setActiveAgentForConversation(dbClient)({
96
+ scopes: { tenantId, projectId },
97
+ conversationId,
98
+ agentId: defaultAgentId,
99
+ });
100
+ }
101
+ const agentId = activeAgent?.activeAgentId || defaultAgentId;
102
+ const agentInfo = await getAgentById(dbClient)({
103
+ scopes: { tenantId, projectId },
104
+ agentId: agentId,
105
+ });
106
+ if (!agentInfo) {
107
+ return c.json({ error: 'Agent not found' }, 404);
108
+ }
109
+ // Get validated context from middleware (falls back to body.context if no validation)
110
+ const validatedContext = c.get('validatedContext') || body.requestContext || {};
111
+ // Context resolution with intelligent conversation state detection
112
+ await handleContextResolution(tenantId, projectId, conversationId, graphId, validatedContext, dbClient);
113
+ // Store last user message
114
+ const lastUserMessage = body.messages.filter((m) => m.role === 'user').slice(-1)[0];
115
+ const userText = typeof lastUserMessage?.content === 'string'
116
+ ? lastUserMessage.content
117
+ : lastUserMessage?.parts?.map((p) => p.text).join('') || '';
118
+ logger.info({ userText, lastUserMessage }, 'userText');
119
+ const messageSpan = trace.getActiveSpan();
120
+ if (messageSpan) {
121
+ messageSpan.setAttributes({
122
+ 'message.timestamp': new Date().toISOString(),
123
+ 'message.content': userText,
124
+ 'graph.name': graphName,
125
+ });
126
+ }
127
+ await createMessage(dbClient)({
128
+ id: nanoid(),
129
+ tenantId,
130
+ projectId,
131
+ conversationId,
132
+ role: 'user',
133
+ content: { text: userText },
134
+ visibility: 'user-facing',
135
+ messageType: 'chat',
136
+ });
137
+ if (messageSpan) {
138
+ messageSpan.addEvent('user.message.stored', {
139
+ 'message.id': conversationId,
140
+ 'database.operation': 'insert',
141
+ });
142
+ }
143
+ // Create UI Message Stream using AI SDK V5
144
+ const dataStream = createUIMessageStream({
145
+ execute: async ({ writer }) => {
146
+ const streamHelper = createVercelStreamHelper(writer);
147
+ try {
148
+ const executionHandler = new ExecutionHandler();
149
+ const result = await executionHandler.execute({
150
+ executionContext,
151
+ conversationId,
152
+ userMessage: userText,
153
+ initialAgentId: agentId,
154
+ requestId: `chatds-${Date.now()}`,
155
+ sseHelper: streamHelper,
156
+ });
157
+ if (!result.success) {
158
+ await streamHelper.writeError('Unable to process request');
159
+ }
160
+ }
161
+ catch (err) {
162
+ logger.error({ err }, 'Streaming error');
163
+ await streamHelper.writeError('Internal server error');
164
+ }
165
+ },
166
+ });
167
+ c.header('content-type', 'text/event-stream');
168
+ c.header('cache-control', 'no-cache');
169
+ c.header('connection', 'keep-alive');
170
+ c.header('x-vercel-ai-data-stream', 'v2');
171
+ c.header('x-accel-buffering', 'no'); // disable nginx buffering
172
+ return stream(c, (stream) => stream.pipe(dataStream.pipeThrough(new JsonToSseTransformStream()).pipeThrough(new TextEncoderStream())));
173
+ }
174
+ catch (error) {
175
+ logger.error({ error }, 'chatDataStream error');
176
+ return c.json({ error: 'Failed to process chat completion' }, 500);
177
+ }
178
+ });
179
+ export default app;
@@ -0,0 +1,4 @@
1
+ import { OpenAPIHono } from '@hono/zod-openapi';
2
+ declare const app: OpenAPIHono<import("hono").Env, {}, "/">;
3
+ export default app;
4
+ //# sourceMappingURL=mcp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../../src/routes/mcp.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAmY7D,QAAA,MAAM,GAAG,0CAAoB,CAAC;AAwT9B,eAAe,GAAG,CAAC"}
@@ -0,0 +1,500 @@
1
+ import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
4
+ import { z } from 'zod/v3';
5
+ import { contextValidationMiddleware, HeadersScopeSchema } from '@inkeep/agents-core';
6
+ // Type bridge for MCP SDK compatibility with Zod v4
7
+ function createMCPSchema(schema) {
8
+ return schema;
9
+ }
10
+ import { trace } from '@opentelemetry/api';
11
+ import { toFetchResponse, toReqRes } from 'fetch-to-node';
12
+ import { nanoid } from 'nanoid';
13
+ import { handleContextResolution } from '@inkeep/agents-core';
14
+ import { createMessage, createOrGetConversation, getAgentGraphWithDefaultAgent, getConversation, getAgentById, updateConversation, getRequestExecutionContext, } from '@inkeep/agents-core';
15
+ import { ExecutionHandler } from '../handlers/executionHandler.js';
16
+ import { getLogger } from '../logger.js';
17
+ import { createMCPStreamHelper } from '../utils/stream-helpers.js';
18
+ import dbClient from '../data/db/dbClient.js';
19
+ const logger = getLogger('mcp');
20
+ /**
21
+ * Singleton mock response object for spoof initialization
22
+ */
23
+ class MockResponseSingleton {
24
+ static instance;
25
+ mockRes;
26
+ constructor() {
27
+ // Create the mock response object once
28
+ this.mockRes = {
29
+ statusCode: 200,
30
+ headers: {},
31
+ setHeader: function (name, value) {
32
+ this.headers[name] = value;
33
+ },
34
+ getHeaders: function () {
35
+ return this.headers;
36
+ },
37
+ end: () => { },
38
+ write: () => { },
39
+ writeHead: () => { },
40
+ };
41
+ }
42
+ static getInstance() {
43
+ if (!MockResponseSingleton.instance) {
44
+ MockResponseSingleton.instance = new MockResponseSingleton();
45
+ }
46
+ return MockResponseSingleton.instance;
47
+ }
48
+ getMockResponse() {
49
+ // Reset headers for each use to avoid state pollution
50
+ this.mockRes.headers = {};
51
+ this.mockRes.statusCode = 200;
52
+ return this.mockRes;
53
+ }
54
+ }
55
+ /**
56
+ * Creates a spoof initialization message with the given protocol version
57
+ * Extracted as a pure function for better testability and reuse
58
+ */
59
+ const createSpoofInitMessage = (mcpProtocolVersion) => ({
60
+ method: 'initialize',
61
+ params: {
62
+ protocolVersion: mcpProtocolVersion || '2025-06-18',
63
+ capabilities: {
64
+ tools: true,
65
+ prompts: true,
66
+ resources: false,
67
+ logging: false,
68
+ roots: { listChanged: false },
69
+ },
70
+ clientInfo: {
71
+ name: 'inkeep-mcp-server',
72
+ version: '1.0.0',
73
+ },
74
+ },
75
+ jsonrpc: '2.0',
76
+ id: 0,
77
+ });
78
+ /**
79
+ * Spoofs an initialization message to set the transport's initialized flag
80
+ * This is necessary when recreating transports for existing sessions because the transport expects to have received an initialization message from the client.
81
+ */
82
+ const spoofTransportInitialization = async (transport, req, sessionId, mcpProtocolVersion) => {
83
+ logger.info({ sessionId }, 'Spoofing initialization message to set transport state');
84
+ const spoofInitMessage = createSpoofInitMessage(mcpProtocolVersion);
85
+ const mockRes = MockResponseSingleton.getInstance().getMockResponse();
86
+ try {
87
+ // Send the spoof initialization to set internal state. The transport errors but it still sets the initialized flag.
88
+ await transport.handleRequest(req, mockRes, spoofInitMessage);
89
+ logger.info({ sessionId }, 'Successfully spoofed initialization');
90
+ }
91
+ catch (spoofError) {
92
+ logger.warn({ sessionId, error: spoofError }, 'Spoof initialization failed, continuing anyway');
93
+ }
94
+ };
95
+ const validateSession = async (req, res, body, tenantId, projectId, graphId) => {
96
+ const sessionId = req.headers['mcp-session-id'];
97
+ logger.info({ sessionId }, 'Received MCP session ID');
98
+ if (!sessionId) {
99
+ logger.info({ body }, 'Missing session ID');
100
+ res.writeHead(400).end(JSON.stringify({
101
+ jsonrpc: '2.0',
102
+ error: { code: -32602, message: 'Bad Request: Mcp-Session-Id header is required' },
103
+ id: null,
104
+ }));
105
+ return false;
106
+ }
107
+ else if (Array.isArray(sessionId)) {
108
+ res.writeHead(400).end(JSON.stringify({
109
+ jsonrpc: '2.0',
110
+ error: {
111
+ code: -32000,
112
+ message: 'Bad Request: Mcp-Session-Id header must be a single value',
113
+ },
114
+ id: null,
115
+ }));
116
+ return false;
117
+ }
118
+ // Get conversation (which stores our session data)
119
+ const conversation = await getConversation(dbClient)({
120
+ scopes: { tenantId, projectId },
121
+ conversationId: sessionId,
122
+ });
123
+ // After line 342 - Add logging to debug conversation lookup
124
+ logger.info({
125
+ sessionId,
126
+ conversationFound: !!conversation,
127
+ sessionType: conversation?.metadata?.sessionData?.sessionType,
128
+ storedGraphId: conversation?.metadata?.sessionData?.graphId,
129
+ requestGraphId: graphId,
130
+ }, 'Conversation lookup result');
131
+ if (!conversation ||
132
+ conversation.metadata?.sessionData?.sessionType !== 'mcp' ||
133
+ conversation.metadata?.sessionData?.graphId !== graphId) {
134
+ logger.info({ sessionId, conversationId: conversation?.id }, 'MCP session not found or invalid');
135
+ res.writeHead(404).end(JSON.stringify({
136
+ jsonrpc: '2.0',
137
+ error: {
138
+ code: -32001,
139
+ message: 'Session not found',
140
+ },
141
+ id: null,
142
+ }));
143
+ return false;
144
+ }
145
+ return conversation;
146
+ };
147
+ /**
148
+ * Sets up tracing attributes for the active span
149
+ */
150
+ const setupTracing = (conversationId, tenantId, graphId) => {
151
+ const activeSpan = trace.getActiveSpan();
152
+ if (activeSpan) {
153
+ activeSpan.setAttributes({
154
+ 'conversation.id': conversationId,
155
+ 'tenant.id': tenantId,
156
+ 'graph.id': graphId,
157
+ });
158
+ }
159
+ };
160
+ /**
161
+ * Processes and stores the user message
162
+ */
163
+ const processUserMessage = async (tenantId, projectId, conversationId, query) => {
164
+ const messageSpan = trace.getActiveSpan();
165
+ if (messageSpan) {
166
+ messageSpan.setAttributes({
167
+ 'message.content': query,
168
+ 'message.timestamp': Date.now(),
169
+ });
170
+ }
171
+ await createMessage(dbClient)({
172
+ id: nanoid(),
173
+ tenantId,
174
+ projectId,
175
+ conversationId,
176
+ role: 'user',
177
+ content: {
178
+ text: query,
179
+ },
180
+ visibility: 'user-facing',
181
+ messageType: 'chat',
182
+ });
183
+ };
184
+ /**
185
+ * Executes the agent query and returns the result
186
+ */
187
+ const executeAgentQuery = async (executionContext, conversationId, query, defaultAgentId) => {
188
+ const requestId = `mcp-${Date.now()}`;
189
+ const mcpStreamHelper = createMCPStreamHelper();
190
+ const executionHandler = new ExecutionHandler();
191
+ const result = await executionHandler.execute({
192
+ executionContext,
193
+ conversationId,
194
+ userMessage: query,
195
+ initialAgentId: defaultAgentId,
196
+ requestId,
197
+ sseHelper: mcpStreamHelper,
198
+ });
199
+ logger.info({ result }, `Execution completed: ${result.success ? 'success' : 'failed'} after ${result.iterations} iterations`);
200
+ if (!result.success) {
201
+ return {
202
+ content: [
203
+ {
204
+ type: 'text',
205
+ text: result.error ||
206
+ `Sorry, I was unable to process your request at this time. Please try again.`,
207
+ },
208
+ ],
209
+ isError: true,
210
+ };
211
+ }
212
+ return {
213
+ content: [
214
+ {
215
+ type: 'text',
216
+ text: result.response || 'No response generated',
217
+ },
218
+ ],
219
+ };
220
+ };
221
+ /**
222
+ * Creates and configures an MCP server for the given context
223
+ */
224
+ const getServer = async (requestContext, executionContext, conversationId) => {
225
+ const { tenantId, projectId, graphId } = executionContext;
226
+ setupTracing(conversationId, tenantId, graphId);
227
+ const agentGraph = await getAgentGraphWithDefaultAgent(dbClient)({
228
+ scopes: { tenantId, projectId },
229
+ graphId: graphId,
230
+ });
231
+ if (!agentGraph) {
232
+ throw new Error('Agent graph not found');
233
+ }
234
+ const server = new McpServer({
235
+ name: 'inkeep-chat-api-server',
236
+ version: '1.0.0',
237
+ }, { capabilities: { logging: {} } });
238
+ // Register tools and prompts
239
+ server.tool('send-query-to-agent', `Send a query to the ${agentGraph.name} agent. The agent has the following description: ${agentGraph.description}`, {
240
+ query: createMCPSchema(z.string().describe('The query to send to the agent')),
241
+ }, async ({ query }) => {
242
+ try {
243
+ const defaultAgentId = agentGraph.defaultAgentId;
244
+ const agentInfo = await getAgentById(dbClient)({
245
+ scopes: { tenantId, projectId },
246
+ agentId: defaultAgentId,
247
+ });
248
+ if (!agentInfo) {
249
+ return {
250
+ content: [
251
+ {
252
+ type: 'text',
253
+ text: `Agent not found`,
254
+ },
255
+ ],
256
+ isError: true,
257
+ };
258
+ }
259
+ const resolvedContext = await handleContextResolution(tenantId, projectId, conversationId, graphId, requestContext, dbClient);
260
+ logger.info({
261
+ tenantId,
262
+ graphId,
263
+ conversationId,
264
+ hasContextConfig: !!agentGraph.contextConfigId,
265
+ hasRequestContext: !!requestContext,
266
+ hasValidatedContext: !!resolvedContext,
267
+ }, 'parameters');
268
+ await processUserMessage(tenantId, projectId, conversationId, query);
269
+ return executeAgentQuery(executionContext, conversationId, query, defaultAgentId);
270
+ }
271
+ catch (error) {
272
+ return {
273
+ content: [
274
+ {
275
+ type: 'text',
276
+ text: `Error sending query: ${error instanceof Error ? error.message : 'Unknown error'}`,
277
+ },
278
+ ],
279
+ isError: true,
280
+ };
281
+ }
282
+ });
283
+ return server;
284
+ };
285
+ const app = new OpenAPIHono();
286
+ // Only apply context validation to POST requests (GET requests are for SSE streams)
287
+ app.use('/', async (c, next) => {
288
+ if (c.req.method === 'POST') {
289
+ return contextValidationMiddleware(dbClient)(c, next);
290
+ }
291
+ return next();
292
+ });
293
+ /**
294
+ * Validates request parameters and returns execution context if valid
295
+ */
296
+ const validateRequestParameters = (c) => {
297
+ try {
298
+ const executionContext = getRequestExecutionContext(c);
299
+ const { tenantId, projectId, graphId } = executionContext;
300
+ getLogger('mcp').debug({ tenantId, projectId, graphId }, 'Extracted MCP entity parameters');
301
+ return { valid: true, executionContext };
302
+ }
303
+ catch (error) {
304
+ getLogger('chat').warn({ error: error instanceof Error ? error.message : 'Unknown error' }, 'Failed to get execution context');
305
+ return {
306
+ valid: false,
307
+ response: c.json({
308
+ jsonrpc: '2.0',
309
+ error: { code: -32602, message: 'API key authentication required' },
310
+ id: null,
311
+ }, { status: 401 }),
312
+ };
313
+ }
314
+ };
315
+ /**
316
+ * Creates a new MCP session and handles initialization
317
+ */
318
+ const handleInitializationRequest = async (body, executionContext, validatedContext, req, res, c) => {
319
+ const { tenantId, projectId, graphId } = executionContext;
320
+ logger.info({ body }, 'Received initialization request');
321
+ const sessionId = nanoid();
322
+ // Get the default agent for the graph
323
+ const agentGraph = await getAgentGraphWithDefaultAgent(dbClient)({
324
+ scopes: { tenantId, projectId },
325
+ graphId,
326
+ });
327
+ if (!agentGraph) {
328
+ return c.json({
329
+ jsonrpc: '2.0',
330
+ error: { code: -32001, message: 'Agent graph not found' },
331
+ id: body.id || null,
332
+ }, { status: 404 });
333
+ }
334
+ // Create/get conversation with MCP session metadata
335
+ const conversation = await createOrGetConversation(dbClient)({
336
+ id: sessionId,
337
+ tenantId,
338
+ projectId,
339
+ activeAgentId: agentGraph.defaultAgentId,
340
+ metadata: {
341
+ sessionData: {
342
+ graphId,
343
+ sessionType: 'mcp',
344
+ mcpProtocolVersion: c.req.header('mcp-protocol-version'),
345
+ initialized: false, // Track initialization state
346
+ },
347
+ },
348
+ });
349
+ logger.info({ sessionId, conversationId: conversation.id }, 'Created MCP session as conversation');
350
+ // Create fresh transport and server for this request
351
+ const transport = new StreamableHTTPServerTransport({
352
+ sessionIdGenerator: () => sessionId,
353
+ });
354
+ const server = await getServer(validatedContext, executionContext, sessionId);
355
+ await server.connect(transport);
356
+ logger.info({ sessionId }, 'Server connected for initialization');
357
+ // Tell client the session ID
358
+ res.setHeader('Mcp-Session-Id', sessionId);
359
+ logger.info({
360
+ sessionId,
361
+ bodyMethod: body?.method,
362
+ bodyId: body?.id,
363
+ }, 'About to handle initialization request');
364
+ await transport.handleRequest(req, res, body);
365
+ logger.info({ sessionId }, 'Successfully handled initialization request');
366
+ return toFetchResponse(res);
367
+ };
368
+ /**
369
+ * Handles requests for existing MCP sessions
370
+ */
371
+ const handleExistingSessionRequest = async (body, executionContext, validatedContext, req, res) => {
372
+ const { tenantId, projectId, graphId } = executionContext;
373
+ // Validate the session id
374
+ const conversation = await validateSession(req, res, body, tenantId, projectId, graphId);
375
+ if (!conversation) {
376
+ return toFetchResponse(res);
377
+ }
378
+ const sessionId = conversation.id;
379
+ // Update last activity
380
+ await updateConversation(dbClient)({
381
+ scopes: { tenantId, projectId },
382
+ conversationId: sessionId,
383
+ data: {
384
+ // Just updating the timestamp by calling update
385
+ },
386
+ });
387
+ // Recreate transport and server from stored session data
388
+ const transport = new StreamableHTTPServerTransport({
389
+ sessionIdGenerator: () => sessionId,
390
+ });
391
+ const server = await getServer(validatedContext, executionContext, sessionId);
392
+ await server.connect(transport);
393
+ // Spoof initialization to set the transport's _initialized flag
394
+ await spoofTransportInitialization(transport, req, sessionId, conversation.metadata?.session_data?.mcpProtocolVersion);
395
+ logger.info({ sessionId }, 'Server connected and transport initialized');
396
+ // Add debugging before transport.handleRequest()
397
+ logger.info({
398
+ sessionId,
399
+ bodyKeys: Object.keys(body || {}),
400
+ bodyMethod: body?.method,
401
+ bodyId: body?.id,
402
+ requestHeaders: Object.fromEntries(Object.entries(req.headers || {}).filter(([k]) => k.startsWith('mcp-'))),
403
+ }, 'About to handle MCP request with existing session');
404
+ try {
405
+ await transport.handleRequest(req, res, body);
406
+ logger.info({ sessionId }, 'Successfully handled MCP request');
407
+ }
408
+ catch (transportError) {
409
+ logger.error({
410
+ sessionId,
411
+ error: transportError,
412
+ errorMessage: transportError instanceof Error ? transportError.message : 'Unknown error',
413
+ }, 'Transport handleRequest failed');
414
+ throw transportError; // Re-throw to be caught by outer catch
415
+ }
416
+ return toFetchResponse(res);
417
+ };
418
+ /**
419
+ * Creates a JSON-RPC error response
420
+ */
421
+ const createErrorResponse = (code, message, id = null) => ({
422
+ jsonrpc: '2.0',
423
+ error: { code, message },
424
+ id,
425
+ });
426
+ app.openapi(createRoute({
427
+ method: 'post',
428
+ path: '/',
429
+ tags: ['MCP'],
430
+ summary: 'MCP Protocol',
431
+ description: 'Handles Model Context Protocol (MCP) JSON-RPC requests',
432
+ security: [{ bearerAuth: [] }],
433
+ request: {
434
+ headers: HeadersScopeSchema,
435
+ },
436
+ responses: {
437
+ 200: {
438
+ description: 'MCP response',
439
+ },
440
+ 401: {
441
+ description: 'Unauthorized - API key authentication required',
442
+ },
443
+ 404: {
444
+ description: 'Not Found - Agent graph not found',
445
+ },
446
+ 500: {
447
+ description: 'Internal Server Error',
448
+ },
449
+ },
450
+ }), async (c) => {
451
+ try {
452
+ // Validate parameters
453
+ const paramValidation = validateRequestParameters(c);
454
+ if (!paramValidation.valid) {
455
+ return paramValidation.response;
456
+ }
457
+ const { executionContext } = paramValidation;
458
+ const body = await c.req.json();
459
+ logger.info({ body, bodyKeys: Object.keys(body || {}) }, 'Parsed request body');
460
+ const isInitRequest = body.method === 'initialize';
461
+ const { req, res } = toReqRes(c.req.raw);
462
+ const validatedContext = c.get('validatedContext') || {};
463
+ logger.info({ validatedContext }, 'Validated context');
464
+ logger.info({ req }, 'request');
465
+ if (isInitRequest) {
466
+ return await handleInitializationRequest(body, executionContext, validatedContext, req, res, c);
467
+ }
468
+ else {
469
+ return await handleExistingSessionRequest(body, executionContext, validatedContext, req, res);
470
+ }
471
+ }
472
+ catch (e) {
473
+ logger.error({
474
+ error: e instanceof Error ? e.message : e,
475
+ stack: e instanceof Error ? e.stack : undefined,
476
+ }, 'MCP request error');
477
+ return c.json(createErrorResponse(-32603, 'Internal server error'), { status: 500 });
478
+ }
479
+ });
480
+ app.get('/', async (c) => {
481
+ logger.info('Received GET MCP request');
482
+ return c.json({
483
+ jsonrpc: '2.0',
484
+ error: {
485
+ code: -32000,
486
+ message: 'Method not allowed.',
487
+ },
488
+ id: null,
489
+ }, { status: 405 });
490
+ });
491
+ // We want to maintain conversations in the database. (https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#session-management)
492
+ app.delete('/', async (c) => {
493
+ logger.info('Received DELETE MCP request');
494
+ return c.json({
495
+ jsonrpc: '2.0',
496
+ error: { code: -32001, message: 'Method Not Allowed' },
497
+ id: null,
498
+ }, { status: 405 });
499
+ });
500
+ export default app;