@inkeep/agents-run-api 0.1.2 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +7 -0
- package/README.md +1 -1
- package/SUPPLEMENTAL_TERMS.md +40 -0
- package/dist/chunk-P6IQZWFC.js +239 -0
- package/dist/conversations-EUPRCMQZ.js +1 -0
- package/dist/index.cjs +8992 -0
- package/dist/index.d.cts +15 -0
- package/dist/index.d.ts +13 -21
- package/dist/index.js +8644 -27
- package/package.json +14 -11
- package/templates/v1/artifact.xml +7 -0
- package/templates/v1/data-component.xml +9 -0
- package/templates/v1/system-prompt.xml +52 -0
- package/templates/v1/thinking-preparation.xml +34 -0
- package/templates/v1/tool.xml +12 -0
- package/dist/AgentExecutionServer.d.ts +0 -28
- package/dist/AgentExecutionServer.d.ts.map +0 -1
- package/dist/AgentExecutionServer.js +0 -41
- package/dist/__tests__/setup.d.ts +0 -4
- package/dist/__tests__/setup.d.ts.map +0 -1
- package/dist/__tests__/setup.js +0 -50
- package/dist/__tests__/utils/testProject.d.ts +0 -18
- package/dist/__tests__/utils/testProject.d.ts.map +0 -1
- package/dist/__tests__/utils/testProject.js +0 -26
- package/dist/__tests__/utils/testRequest.d.ts +0 -8
- package/dist/__tests__/utils/testRequest.d.ts.map +0 -1
- package/dist/__tests__/utils/testRequest.js +0 -32
- package/dist/__tests__/utils/testTenant.d.ts +0 -64
- package/dist/__tests__/utils/testTenant.d.ts.map +0 -1
- package/dist/__tests__/utils/testTenant.js +0 -71
- package/dist/a2a/client.d.ts +0 -182
- package/dist/a2a/client.d.ts.map +0 -1
- package/dist/a2a/client.js +0 -645
- package/dist/a2a/handlers.d.ts +0 -4
- package/dist/a2a/handlers.d.ts.map +0 -1
- package/dist/a2a/handlers.js +0 -657
- package/dist/a2a/transfer.d.ts +0 -18
- package/dist/a2a/transfer.d.ts.map +0 -1
- package/dist/a2a/transfer.js +0 -22
- package/dist/a2a/types.d.ts +0 -63
- package/dist/a2a/types.d.ts.map +0 -1
- package/dist/a2a/types.js +0 -1
- package/dist/agents/Agent.d.ts +0 -154
- package/dist/agents/Agent.d.ts.map +0 -1
- package/dist/agents/Agent.js +0 -1107
- package/dist/agents/ModelFactory.d.ts +0 -62
- package/dist/agents/ModelFactory.d.ts.map +0 -1
- package/dist/agents/ModelFactory.js +0 -208
- package/dist/agents/SystemPromptBuilder.d.ts +0 -14
- package/dist/agents/SystemPromptBuilder.d.ts.map +0 -1
- package/dist/agents/SystemPromptBuilder.js +0 -62
- package/dist/agents/ToolSessionManager.d.ts +0 -61
- package/dist/agents/ToolSessionManager.d.ts.map +0 -1
- package/dist/agents/ToolSessionManager.js +0 -143
- package/dist/agents/artifactTools.d.ts +0 -30
- package/dist/agents/artifactTools.d.ts.map +0 -1
- package/dist/agents/artifactTools.js +0 -463
- package/dist/agents/generateTaskHandler.d.ts +0 -41
- package/dist/agents/generateTaskHandler.d.ts.map +0 -1
- package/dist/agents/generateTaskHandler.js +0 -350
- package/dist/agents/relationTools.d.ts +0 -35
- package/dist/agents/relationTools.d.ts.map +0 -1
- package/dist/agents/relationTools.js +0 -244
- package/dist/agents/types.d.ts +0 -23
- package/dist/agents/types.d.ts.map +0 -1
- package/dist/agents/types.js +0 -1
- package/dist/agents/versions/V1Config.d.ts +0 -21
- package/dist/agents/versions/V1Config.d.ts.map +0 -1
- package/dist/agents/versions/V1Config.js +0 -285
- package/dist/app.d.ts +0 -12
- package/dist/app.d.ts.map +0 -1
- package/dist/app.js +0 -202
- package/dist/data/agentGraph.d.ts +0 -4
- package/dist/data/agentGraph.d.ts.map +0 -1
- package/dist/data/agentGraph.js +0 -73
- package/dist/data/agents.d.ts +0 -4
- package/dist/data/agents.d.ts.map +0 -1
- package/dist/data/agents.js +0 -73
- package/dist/data/conversations.d.ts +0 -59
- package/dist/data/conversations.d.ts.map +0 -1
- package/dist/data/conversations.js +0 -216
- package/dist/data/db/clean.d.ts +0 -6
- package/dist/data/db/clean.d.ts.map +0 -1
- package/dist/data/db/clean.js +0 -77
- package/dist/data/db/dbClient.d.ts +0 -3
- package/dist/data/db/dbClient.d.ts.map +0 -1
- package/dist/data/db/dbClient.js +0 -13
- package/dist/env.d.ts +0 -45
- package/dist/env.d.ts.map +0 -1
- package/dist/env.js +0 -64
- package/dist/handlers/executionHandler.d.ts +0 -36
- package/dist/handlers/executionHandler.d.ts.map +0 -1
- package/dist/handlers/executionHandler.js +0 -399
- package/dist/index.d.ts.map +0 -1
- package/dist/instrumentation.d.ts +0 -13
- package/dist/instrumentation.d.ts.map +0 -1
- package/dist/instrumentation.js +0 -66
- package/dist/logger.d.ts +0 -4
- package/dist/logger.d.ts.map +0 -1
- package/dist/logger.js +0 -32
- package/dist/middleware/api-key-auth.d.ts +0 -22
- package/dist/middleware/api-key-auth.d.ts.map +0 -1
- package/dist/middleware/api-key-auth.js +0 -139
- package/dist/middleware/index.d.ts +0 -2
- package/dist/middleware/index.d.ts.map +0 -1
- package/dist/middleware/index.js +0 -1
- package/dist/openapi.d.ts +0 -2
- package/dist/openapi.d.ts.map +0 -1
- package/dist/openapi.js +0 -36
- package/dist/routes/agents.d.ts +0 -10
- package/dist/routes/agents.d.ts.map +0 -1
- package/dist/routes/agents.js +0 -158
- package/dist/routes/chat.d.ts +0 -4
- package/dist/routes/chat.d.ts.map +0 -1
- package/dist/routes/chat.js +0 -308
- package/dist/routes/chatDataStream.d.ts +0 -4
- package/dist/routes/chatDataStream.d.ts.map +0 -1
- package/dist/routes/chatDataStream.js +0 -179
- package/dist/routes/mcp.d.ts +0 -4
- package/dist/routes/mcp.d.ts.map +0 -1
- package/dist/routes/mcp.js +0 -500
- package/dist/server.d.ts +0 -5
- package/dist/server.d.ts.map +0 -1
- package/dist/server.js +0 -61
- package/dist/tracer.d.ts +0 -24
- package/dist/tracer.d.ts.map +0 -1
- package/dist/tracer.js +0 -106
- package/dist/types/chat.d.ts +0 -25
- package/dist/types/chat.d.ts.map +0 -1
- package/dist/types/chat.js +0 -1
- package/dist/types/execution-context.d.ts +0 -14
- package/dist/types/execution-context.d.ts.map +0 -1
- package/dist/types/execution-context.js +0 -14
- package/dist/utils/agent-operations.d.ts +0 -92
- package/dist/utils/agent-operations.d.ts.map +0 -1
- package/dist/utils/agent-operations.js +0 -78
- package/dist/utils/artifact-component-schema.d.ts +0 -29
- package/dist/utils/artifact-component-schema.d.ts.map +0 -1
- package/dist/utils/artifact-component-schema.js +0 -119
- package/dist/utils/artifact-parser.d.ts +0 -71
- package/dist/utils/artifact-parser.d.ts.map +0 -1
- package/dist/utils/artifact-parser.js +0 -251
- package/dist/utils/cleanup.d.ts +0 -19
- package/dist/utils/cleanup.d.ts.map +0 -1
- package/dist/utils/cleanup.js +0 -66
- package/dist/utils/data-component-schema.d.ts +0 -6
- package/dist/utils/data-component-schema.d.ts.map +0 -1
- package/dist/utils/data-component-schema.js +0 -43
- package/dist/utils/graph-session.d.ts +0 -200
- package/dist/utils/graph-session.d.ts.map +0 -1
- package/dist/utils/graph-session.js +0 -1012
- package/dist/utils/incremental-stream-parser.d.ts +0 -57
- package/dist/utils/incremental-stream-parser.d.ts.map +0 -1
- package/dist/utils/incremental-stream-parser.js +0 -287
- package/dist/utils/response-formatter.d.ts +0 -27
- package/dist/utils/response-formatter.d.ts.map +0 -1
- package/dist/utils/response-formatter.js +0 -160
- package/dist/utils/stream-helpers.d.ts +0 -174
- package/dist/utils/stream-helpers.d.ts.map +0 -1
- package/dist/utils/stream-helpers.js +0 -466
- package/dist/utils/stream-registry.d.ts +0 -18
- package/dist/utils/stream-registry.d.ts.map +0 -1
- package/dist/utils/stream-registry.js +0 -33
package/dist/routes/mcp.js
DELETED
|
@@ -1,500 +0,0 @@
|
|
|
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;
|
package/dist/server.d.ts
DELETED
package/dist/server.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,sBAAsB,CAAC;AAM9B,OAAO,EAAE,oBAAoB,EAAsB,MAAM,2BAA2B,CAAC;AAsBrF,QAAA,MAAM,eAAe,sBAQnB,CAAC;AAmCH,OAAO,EAAE,eAAe,EAAE,CAAC"}
|
package/dist/server.js
DELETED
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
import './instrumentation.js';
|
|
2
|
-
import { createKeyChainStore, createNangoCredentialStore, InMemoryCredentialStore, } from '@inkeep/agents-core';
|
|
3
|
-
import { AgentExecutionServer, EXECUTION_API_PORT } from './AgentExecutionServer.js';
|
|
4
|
-
import { env } from './env.js';
|
|
5
|
-
import { getLogger } from './logger.js';
|
|
6
|
-
const logger = getLogger('execution-api');
|
|
7
|
-
// Create credential stores
|
|
8
|
-
const credentialStores = [
|
|
9
|
-
new InMemoryCredentialStore('memory-default'), // In-memory store + env vars
|
|
10
|
-
// Nango store (only loads if NANGO_SECRET_KEY is set)
|
|
11
|
-
...(process.env.NANGO_SECRET_KEY
|
|
12
|
-
? [
|
|
13
|
-
createNangoCredentialStore('nango-default', {
|
|
14
|
-
apiUrl: process.env.NANGO_HOST || 'https://api.nango.dev',
|
|
15
|
-
secretKey: process.env.NANGO_SECRET_KEY,
|
|
16
|
-
}),
|
|
17
|
-
]
|
|
18
|
-
: []),
|
|
19
|
-
createKeyChainStore('keychain-default'),
|
|
20
|
-
];
|
|
21
|
-
// Initialize Execution Server
|
|
22
|
-
const executionServer = new AgentExecutionServer({
|
|
23
|
-
port: EXECUTION_API_PORT,
|
|
24
|
-
credentialStores,
|
|
25
|
-
serverOptions: {
|
|
26
|
-
requestTimeout: 120000, // 120 seconds for execution requests
|
|
27
|
-
keepAliveTimeout: 60000,
|
|
28
|
-
keepAlive: true,
|
|
29
|
-
},
|
|
30
|
-
});
|
|
31
|
-
// Start the server only if not in test environment AND not using Vite dev server
|
|
32
|
-
const isViteDevServer = process.env.NODE_ENV === 'development' &&
|
|
33
|
-
(process.env.VITE_DEV_SERVER === 'true' ||
|
|
34
|
-
process.env.VITE !== undefined ||
|
|
35
|
-
process.argv.some((arg) => arg.includes('vite')) ||
|
|
36
|
-
globalThis.__vite_dev_server__);
|
|
37
|
-
if (env.ENVIRONMENT !== 'test' && !isViteDevServer) {
|
|
38
|
-
executionServer
|
|
39
|
-
.serve()
|
|
40
|
-
.then(() => {
|
|
41
|
-
logger.info(`📝 OpenAPI documentation available at http://localhost:${EXECUTION_API_PORT}/openapi.json`);
|
|
42
|
-
})
|
|
43
|
-
.catch((error) => {
|
|
44
|
-
logger.error('Failed to start Execution API server:', error);
|
|
45
|
-
process.exit(1);
|
|
46
|
-
});
|
|
47
|
-
}
|
|
48
|
-
else if (isViteDevServer) {
|
|
49
|
-
// Initialize server (credential stores, etc.) but don't start HTTP server - Vite handles that
|
|
50
|
-
(async () => {
|
|
51
|
-
try {
|
|
52
|
-
await executionServer.initializeOnly();
|
|
53
|
-
logger.info('🚀 Execution server initialized for Vite dev mode (credential stores ready)');
|
|
54
|
-
logger.info('🔥 HTTP server handled by Vite dev server');
|
|
55
|
-
}
|
|
56
|
-
catch (error) {
|
|
57
|
-
logger.error('Failed to initialize execution server:', error);
|
|
58
|
-
}
|
|
59
|
-
})();
|
|
60
|
-
}
|
|
61
|
-
export { executionServer };
|
package/dist/tracer.d.ts
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { type Span, type Tracer } from '@opentelemetry/api';
|
|
2
|
-
export declare const BASE = "inkeep-chat";
|
|
3
|
-
export declare const SERVICE_NAME = "inkeep-chat";
|
|
4
|
-
export declare const SERVICE_VERSION = "1.0.0";
|
|
5
|
-
export declare const createSpanName: (suffix: string) => string;
|
|
6
|
-
/**
|
|
7
|
-
* Helper function to handle span errors consistently
|
|
8
|
-
* Records the exception, sets error status, and optionally logs
|
|
9
|
-
*/
|
|
10
|
-
export declare function handleSpanError(span: Span, error: unknown, logger?: {
|
|
11
|
-
error: (obj: any, msg?: string) => void;
|
|
12
|
-
}, logMessage?: string): void;
|
|
13
|
-
/**
|
|
14
|
-
* Get the global tracer instance
|
|
15
|
-
* This creates a single tracer for the entire application
|
|
16
|
-
*/
|
|
17
|
-
export declare function getGlobalTracer(): Tracer;
|
|
18
|
-
/**
|
|
19
|
-
* Force flush the tracer provider to ensure critical spans are sent immediately
|
|
20
|
-
* This is useful for critical operations where we want to ensure telemetry data
|
|
21
|
-
* is sent before the operation completes or fails
|
|
22
|
-
*/
|
|
23
|
-
export declare function forceFlushTracer(): Promise<void>;
|
|
24
|
-
//# sourceMappingURL=tracer.d.ts.map
|
package/dist/tracer.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tracer.d.ts","sourceRoot":"","sources":["../src/tracer.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,IAAI,EAGT,KAAK,MAAM,EAEZ,MAAM,oBAAoB,CAAC;AAU5B,eAAO,MAAM,IAAI,gBAAgB,CAAC;AAGlC,eAAO,MAAM,YAAY,gBAAgB,CAAC;AAC1C,eAAO,MAAM,eAAe,UAAU,CAAC;AAGvC,eAAO,MAAM,cAAc,GAAI,QAAQ,MAAM,WAAwB,CAAC;AAyCtE;;;GAGG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,IAAI,EACV,KAAK,EAAE,OAAO,EACd,MAAM,CAAC,EAAE;IAAE,KAAK,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAAE,MAAM,KAAK,IAAI,CAAA;CAAE,EACpD,UAAU,CAAC,EAAE,MAAM,GAClB,IAAI,CAgBN;AAED;;;GAGG;AACH,wBAAgB,eAAe,IAAI,MAAM,CAUxC;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC,CAsBtD"}
|