@contractspec/bundle.library 3.0.0 → 3.2.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.
- package/.turbo/turbo-build.log +178 -166
- package/AGENTS.md +19 -12
- package/CHANGELOG.md +74 -0
- package/dist/application/context-storage/index.d.ts +18 -0
- package/dist/application/context-storage/index.js +29 -0
- package/dist/application/index.d.ts +1 -0
- package/dist/application/index.js +662 -2
- package/dist/application/mcp/cliMcp.js +12 -2
- package/dist/application/mcp/common.d.ts +11 -1
- package/dist/application/mcp/common.js +12 -2
- package/dist/application/mcp/contractsMcp.d.ts +51 -0
- package/dist/application/mcp/contractsMcp.js +531 -0
- package/dist/application/mcp/contractsMcpResources.d.ts +7 -0
- package/dist/application/mcp/contractsMcpResources.js +124 -0
- package/dist/application/mcp/contractsMcpTools.d.ts +9 -0
- package/dist/application/mcp/contractsMcpTools.js +200 -0
- package/dist/application/mcp/contractsMcpTypes.d.ts +50 -0
- package/dist/application/mcp/contractsMcpTypes.js +1 -0
- package/dist/application/mcp/docsMcp.js +12 -2
- package/dist/application/mcp/index.d.ts +2 -0
- package/dist/application/mcp/index.js +635 -2
- package/dist/application/mcp/internalMcp.js +12 -2
- package/dist/application/mcp/providerRankingMcp.d.ts +46 -0
- package/dist/application/mcp/providerRankingMcp.js +494 -0
- package/dist/node/application/context-storage/index.js +28 -0
- package/dist/node/application/index.js +662 -2
- package/dist/node/application/mcp/cliMcp.js +12 -2
- package/dist/node/application/mcp/common.js +12 -2
- package/dist/node/application/mcp/contractsMcp.js +530 -0
- package/dist/node/application/mcp/contractsMcpResources.js +123 -0
- package/dist/node/application/mcp/contractsMcpTools.js +199 -0
- package/dist/node/application/mcp/contractsMcpTypes.js +0 -0
- package/dist/node/application/mcp/docsMcp.js +12 -2
- package/dist/node/application/mcp/index.js +635 -2
- package/dist/node/application/mcp/internalMcp.js +12 -2
- package/dist/node/application/mcp/providerRankingMcp.js +493 -0
- package/package.json +113 -25
- package/src/application/context-storage/index.ts +58 -0
- package/src/application/index.ts +1 -0
- package/src/application/mcp/common.ts +28 -1
- package/src/application/mcp/contractsMcp.ts +34 -0
- package/src/application/mcp/contractsMcpResources.ts +142 -0
- package/src/application/mcp/contractsMcpTools.ts +246 -0
- package/src/application/mcp/contractsMcpTypes.ts +47 -0
- package/src/application/mcp/index.ts +2 -0
- package/src/application/mcp/providerRankingMcp.ts +380 -0
- package/src/components/docs/generated/docs-index._common.json +879 -1
- package/src/components/docs/generated/docs-index.manifest.json +5 -5
- package/src/components/docs/generated/docs-index.metrics.json +8 -0
- package/src/components/docs/generated/docs-index.platform-integrations.json +8 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { ProviderRankingStore } from '@contractspec/lib.provider-ranking/store';
|
|
2
|
+
export declare function createProviderRankingMcpHandler(path?: string): import("elysia").default<"", {
|
|
3
|
+
decorator: {};
|
|
4
|
+
store: {};
|
|
5
|
+
derive: {};
|
|
6
|
+
resolve: {};
|
|
7
|
+
}, {
|
|
8
|
+
typebox: {};
|
|
9
|
+
error: {};
|
|
10
|
+
}, {
|
|
11
|
+
schema: {};
|
|
12
|
+
standaloneSchema: {};
|
|
13
|
+
macro: {};
|
|
14
|
+
macroFn: {};
|
|
15
|
+
parser: {};
|
|
16
|
+
response: {};
|
|
17
|
+
}, {
|
|
18
|
+
[x: string]: {
|
|
19
|
+
[x: string]: {
|
|
20
|
+
body: unknown;
|
|
21
|
+
params: {};
|
|
22
|
+
query: unknown;
|
|
23
|
+
headers: unknown;
|
|
24
|
+
response: {
|
|
25
|
+
200: Response;
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
}, {
|
|
30
|
+
derive: {};
|
|
31
|
+
resolve: {};
|
|
32
|
+
schema: {};
|
|
33
|
+
standaloneSchema: {};
|
|
34
|
+
response: {};
|
|
35
|
+
}, {
|
|
36
|
+
derive: {};
|
|
37
|
+
resolve: {};
|
|
38
|
+
schema: {};
|
|
39
|
+
standaloneSchema: {};
|
|
40
|
+
response: {};
|
|
41
|
+
}>;
|
|
42
|
+
/**
|
|
43
|
+
* Allows external callers to inject a custom store
|
|
44
|
+
* (e.g. PostgresProviderRankingStore from the module layer).
|
|
45
|
+
*/
|
|
46
|
+
export declare function setProviderRankingStore(store: ProviderRankingStore): void;
|
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/application/mcp/common.ts
|
|
3
|
+
import { PresentationRegistry } from "@contractspec/lib.contracts-spec/presentations";
|
|
4
|
+
import { createMcpServer } from "@contractspec/lib.contracts-runtime-server-mcp/provider-mcp";
|
|
5
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
6
|
+
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
7
|
+
import { Elysia } from "elysia";
|
|
8
|
+
import { randomUUID } from "crypto";
|
|
9
|
+
var baseCtx = {
|
|
10
|
+
actor: "anonymous",
|
|
11
|
+
decide: async () => ({ effect: "allow" })
|
|
12
|
+
};
|
|
13
|
+
function createJsonRpcErrorResponse(status, code, message, data) {
|
|
14
|
+
return new Response(JSON.stringify({
|
|
15
|
+
jsonrpc: "2.0",
|
|
16
|
+
error: {
|
|
17
|
+
code,
|
|
18
|
+
message,
|
|
19
|
+
...data ? { data } : {}
|
|
20
|
+
},
|
|
21
|
+
id: null
|
|
22
|
+
}), {
|
|
23
|
+
status,
|
|
24
|
+
headers: {
|
|
25
|
+
"content-type": "application/json"
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
function createSessionState({
|
|
30
|
+
logger,
|
|
31
|
+
serverName,
|
|
32
|
+
ops,
|
|
33
|
+
resources,
|
|
34
|
+
prompts,
|
|
35
|
+
presentations,
|
|
36
|
+
stateful
|
|
37
|
+
}) {
|
|
38
|
+
const server = new McpServer({
|
|
39
|
+
name: serverName,
|
|
40
|
+
version: "1.0.0"
|
|
41
|
+
}, {
|
|
42
|
+
capabilities: {
|
|
43
|
+
tools: {},
|
|
44
|
+
resources: {},
|
|
45
|
+
prompts: {},
|
|
46
|
+
logging: {}
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
logger.info("Setting up MCP server...");
|
|
50
|
+
createMcpServer(server, ops, resources, prompts, {
|
|
51
|
+
logger,
|
|
52
|
+
toolCtx: () => baseCtx,
|
|
53
|
+
promptCtx: () => ({ locale: "en" }),
|
|
54
|
+
resourceCtx: () => ({ locale: "en" }),
|
|
55
|
+
presentations: new PresentationRegistry(presentations)
|
|
56
|
+
});
|
|
57
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
58
|
+
sessionIdGenerator: stateful ? () => randomUUID() : undefined,
|
|
59
|
+
enableJsonResponse: true
|
|
60
|
+
});
|
|
61
|
+
return server.connect(transport).then(() => ({ server, transport }));
|
|
62
|
+
}
|
|
63
|
+
async function closeSessionState(state) {
|
|
64
|
+
await Promise.allSettled([state.transport.close(), state.server.close()]);
|
|
65
|
+
}
|
|
66
|
+
function toErrorMessage(error) {
|
|
67
|
+
return error instanceof Error ? error.stack ?? error.message : String(error);
|
|
68
|
+
}
|
|
69
|
+
function createMcpElysiaHandler({
|
|
70
|
+
logger,
|
|
71
|
+
path,
|
|
72
|
+
serverName,
|
|
73
|
+
ops,
|
|
74
|
+
resources,
|
|
75
|
+
prompts,
|
|
76
|
+
presentations,
|
|
77
|
+
validateAuth,
|
|
78
|
+
requiredAuthMethods
|
|
79
|
+
}) {
|
|
80
|
+
logger.info("Setting up MCP handler...", {
|
|
81
|
+
requiredAuthMethods: requiredAuthMethods ?? []
|
|
82
|
+
});
|
|
83
|
+
const isStateful = process.env.CONTRACTSPEC_MCP_STATEFUL === "1";
|
|
84
|
+
const sessions = new Map;
|
|
85
|
+
async function handleStateless(request) {
|
|
86
|
+
const state = await createSessionState({
|
|
87
|
+
logger,
|
|
88
|
+
path,
|
|
89
|
+
serverName,
|
|
90
|
+
ops,
|
|
91
|
+
resources,
|
|
92
|
+
prompts,
|
|
93
|
+
presentations,
|
|
94
|
+
stateful: false
|
|
95
|
+
});
|
|
96
|
+
try {
|
|
97
|
+
return await state.transport.handleRequest(request);
|
|
98
|
+
} finally {
|
|
99
|
+
await closeSessionState(state);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
async function closeSession(sessionId) {
|
|
103
|
+
const state = sessions.get(sessionId);
|
|
104
|
+
if (!state)
|
|
105
|
+
return;
|
|
106
|
+
sessions.delete(sessionId);
|
|
107
|
+
await closeSessionState(state);
|
|
108
|
+
}
|
|
109
|
+
async function handleStateful(request) {
|
|
110
|
+
const requestedSessionId = request.headers.get("mcp-session-id");
|
|
111
|
+
let state;
|
|
112
|
+
let createdState = false;
|
|
113
|
+
if (requestedSessionId) {
|
|
114
|
+
const existing = sessions.get(requestedSessionId);
|
|
115
|
+
if (!existing) {
|
|
116
|
+
return createJsonRpcErrorResponse(404, -32001, "Session not found");
|
|
117
|
+
}
|
|
118
|
+
state = existing;
|
|
119
|
+
} else {
|
|
120
|
+
state = await createSessionState({
|
|
121
|
+
logger,
|
|
122
|
+
path,
|
|
123
|
+
serverName,
|
|
124
|
+
ops,
|
|
125
|
+
resources,
|
|
126
|
+
prompts,
|
|
127
|
+
presentations,
|
|
128
|
+
stateful: true
|
|
129
|
+
});
|
|
130
|
+
createdState = true;
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
const response = await state.transport.handleRequest(request);
|
|
134
|
+
const activeSessionId = state.transport.sessionId;
|
|
135
|
+
if (activeSessionId && !sessions.has(activeSessionId)) {
|
|
136
|
+
sessions.set(activeSessionId, state);
|
|
137
|
+
}
|
|
138
|
+
if (request.method === "DELETE" && activeSessionId) {
|
|
139
|
+
await closeSession(activeSessionId);
|
|
140
|
+
} else if (!activeSessionId && createdState) {
|
|
141
|
+
await closeSessionState(state);
|
|
142
|
+
}
|
|
143
|
+
return response;
|
|
144
|
+
} catch (error) {
|
|
145
|
+
if (createdState) {
|
|
146
|
+
await closeSessionState(state);
|
|
147
|
+
}
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return new Elysia({ name: `mcp-${serverName}` }).all(path, async ({ request }) => {
|
|
152
|
+
try {
|
|
153
|
+
if (validateAuth) {
|
|
154
|
+
const authResult = await validateAuth(request);
|
|
155
|
+
if (!authResult.valid) {
|
|
156
|
+
return createJsonRpcErrorResponse(401, -32002, "Authentication failed", authResult.reason);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (isStateful) {
|
|
160
|
+
return await handleStateful(request);
|
|
161
|
+
}
|
|
162
|
+
return await handleStateless(request);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
logger.error("Error handling MCP request", {
|
|
165
|
+
path,
|
|
166
|
+
method: request.method,
|
|
167
|
+
error: toErrorMessage(error)
|
|
168
|
+
});
|
|
169
|
+
return createJsonRpcErrorResponse(500, -32000, "Internal error");
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// src/infrastructure/elysia/logger.ts
|
|
175
|
+
import { Logger, LogLevel } from "@contractspec/lib.logger";
|
|
176
|
+
var createAppLogger = () => new Logger({
|
|
177
|
+
level: LogLevel.DEBUG,
|
|
178
|
+
environment: "development",
|
|
179
|
+
enableTracing: true,
|
|
180
|
+
enableTiming: true,
|
|
181
|
+
enableContext: true,
|
|
182
|
+
enableColors: true
|
|
183
|
+
});
|
|
184
|
+
var appLogger = createAppLogger();
|
|
185
|
+
var dbLogger = new Logger({
|
|
186
|
+
level: LogLevel.DEBUG,
|
|
187
|
+
environment: "development",
|
|
188
|
+
enableTracing: true,
|
|
189
|
+
enableTiming: true,
|
|
190
|
+
enableContext: true,
|
|
191
|
+
enableColors: true
|
|
192
|
+
});
|
|
193
|
+
var authLogger = new Logger({
|
|
194
|
+
level: LogLevel.INFO,
|
|
195
|
+
environment: "development",
|
|
196
|
+
enableTracing: true,
|
|
197
|
+
enableTiming: true,
|
|
198
|
+
enableContext: true,
|
|
199
|
+
enableColors: true
|
|
200
|
+
});
|
|
201
|
+
// src/application/mcp/providerRankingMcp.ts
|
|
202
|
+
import {
|
|
203
|
+
definePrompt,
|
|
204
|
+
defineResourceTemplate,
|
|
205
|
+
installOp,
|
|
206
|
+
OperationSpecRegistry,
|
|
207
|
+
PromptRegistry,
|
|
208
|
+
ResourceRegistry
|
|
209
|
+
} from "@contractspec/lib.contracts-spec";
|
|
210
|
+
import {
|
|
211
|
+
BenchmarkIngestCommand,
|
|
212
|
+
BenchmarkRunCustomCommand,
|
|
213
|
+
RankingRefreshCommand
|
|
214
|
+
} from "@contractspec/lib.contracts-spec/provider-ranking";
|
|
215
|
+
import z from "zod";
|
|
216
|
+
import { InMemoryProviderRankingStore } from "@contractspec/lib.provider-ranking/in-memory-store";
|
|
217
|
+
import { createDefaultIngesterRegistry } from "@contractspec/lib.provider-ranking/ingesters";
|
|
218
|
+
import { computeModelRankings } from "@contractspec/lib.provider-ranking/scoring";
|
|
219
|
+
import { normalizeBenchmarkResults } from "@contractspec/lib.provider-ranking/scoring";
|
|
220
|
+
var TransportFilterSchema = z.enum(["rest", "mcp", "webhook", "sdk"]).optional();
|
|
221
|
+
var AuthFilterSchema = z.enum([
|
|
222
|
+
"api-key",
|
|
223
|
+
"oauth2",
|
|
224
|
+
"bearer",
|
|
225
|
+
"header",
|
|
226
|
+
"basic",
|
|
227
|
+
"webhook-signing",
|
|
228
|
+
"service-account"
|
|
229
|
+
]).optional();
|
|
230
|
+
var RANKING_TAGS = ["ranking", "mcp", "ai"];
|
|
231
|
+
var RANKING_OWNERS = ["platform.ai"];
|
|
232
|
+
var sharedStore = null;
|
|
233
|
+
function getStore() {
|
|
234
|
+
if (!sharedStore) {
|
|
235
|
+
sharedStore = new InMemoryProviderRankingStore;
|
|
236
|
+
}
|
|
237
|
+
return sharedStore;
|
|
238
|
+
}
|
|
239
|
+
function buildRankingResources() {
|
|
240
|
+
const resources = new ResourceRegistry;
|
|
241
|
+
resources.register(defineResourceTemplate({
|
|
242
|
+
meta: {
|
|
243
|
+
uriTemplate: "ranking://leaderboard",
|
|
244
|
+
title: "AI Model Leaderboard",
|
|
245
|
+
description: "Current ranked list of AI models by composite score. Supports optional transport and authMethod query filters.",
|
|
246
|
+
mimeType: "application/json",
|
|
247
|
+
tags: RANKING_TAGS
|
|
248
|
+
},
|
|
249
|
+
input: z.object({
|
|
250
|
+
transport: TransportFilterSchema,
|
|
251
|
+
authMethod: AuthFilterSchema
|
|
252
|
+
}),
|
|
253
|
+
resolve: async ({ transport, authMethod }) => {
|
|
254
|
+
const store = getStore();
|
|
255
|
+
const result = await store.listModelRankings({
|
|
256
|
+
limit: 100,
|
|
257
|
+
requiredTransport: transport,
|
|
258
|
+
requiredAuthMethod: authMethod
|
|
259
|
+
});
|
|
260
|
+
return {
|
|
261
|
+
uri: "ranking://leaderboard",
|
|
262
|
+
mimeType: "application/json",
|
|
263
|
+
data: JSON.stringify(result, null, 2)
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
}));
|
|
267
|
+
resources.register(defineResourceTemplate({
|
|
268
|
+
meta: {
|
|
269
|
+
uriTemplate: "ranking://leaderboard/{dimension}",
|
|
270
|
+
title: "AI Model Leaderboard by Dimension",
|
|
271
|
+
description: "Ranked list of AI models filtered by a specific dimension. Supports optional transport and authMethod query filters.",
|
|
272
|
+
mimeType: "application/json",
|
|
273
|
+
tags: RANKING_TAGS
|
|
274
|
+
},
|
|
275
|
+
input: z.object({
|
|
276
|
+
dimension: z.string(),
|
|
277
|
+
transport: TransportFilterSchema,
|
|
278
|
+
authMethod: AuthFilterSchema
|
|
279
|
+
}),
|
|
280
|
+
resolve: async ({ dimension, transport, authMethod }) => {
|
|
281
|
+
const store = getStore();
|
|
282
|
+
const result = await store.listModelRankings({
|
|
283
|
+
dimension,
|
|
284
|
+
limit: 100,
|
|
285
|
+
requiredTransport: transport,
|
|
286
|
+
requiredAuthMethod: authMethod
|
|
287
|
+
});
|
|
288
|
+
return {
|
|
289
|
+
uri: `ranking://leaderboard/${encodeURIComponent(dimension)}`,
|
|
290
|
+
mimeType: "application/json",
|
|
291
|
+
data: JSON.stringify(result, null, 2)
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
}));
|
|
295
|
+
resources.register(defineResourceTemplate({
|
|
296
|
+
meta: {
|
|
297
|
+
uriTemplate: "ranking://model/{modelId}",
|
|
298
|
+
title: "AI Model Profile",
|
|
299
|
+
description: "Detailed profile for a specific AI model including scores and benchmarks.",
|
|
300
|
+
mimeType: "application/json",
|
|
301
|
+
tags: RANKING_TAGS
|
|
302
|
+
},
|
|
303
|
+
input: z.object({ modelId: z.string() }),
|
|
304
|
+
resolve: async ({ modelId }) => {
|
|
305
|
+
const store = getStore();
|
|
306
|
+
const profile = await store.getModelProfile(modelId);
|
|
307
|
+
if (!profile) {
|
|
308
|
+
return {
|
|
309
|
+
uri: `ranking://model/${encodeURIComponent(modelId)}`,
|
|
310
|
+
mimeType: "application/json",
|
|
311
|
+
data: JSON.stringify({ error: "not_found", modelId })
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
return {
|
|
315
|
+
uri: `ranking://model/${encodeURIComponent(modelId)}`,
|
|
316
|
+
mimeType: "application/json",
|
|
317
|
+
data: JSON.stringify(profile, null, 2)
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
}));
|
|
321
|
+
resources.register(defineResourceTemplate({
|
|
322
|
+
meta: {
|
|
323
|
+
uriTemplate: "ranking://results",
|
|
324
|
+
title: "Benchmark Results",
|
|
325
|
+
description: "List of raw benchmark results from all ingested sources.",
|
|
326
|
+
mimeType: "application/json",
|
|
327
|
+
tags: RANKING_TAGS
|
|
328
|
+
},
|
|
329
|
+
input: z.object({}),
|
|
330
|
+
resolve: async () => {
|
|
331
|
+
const store = getStore();
|
|
332
|
+
const result = await store.listBenchmarkResults({ limit: 200 });
|
|
333
|
+
return {
|
|
334
|
+
uri: "ranking://results",
|
|
335
|
+
mimeType: "application/json",
|
|
336
|
+
data: JSON.stringify(result, null, 2)
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
}));
|
|
340
|
+
return resources;
|
|
341
|
+
}
|
|
342
|
+
function buildRankingPrompts() {
|
|
343
|
+
const prompts = new PromptRegistry;
|
|
344
|
+
prompts.register(definePrompt({
|
|
345
|
+
meta: {
|
|
346
|
+
key: "ranking.advisor",
|
|
347
|
+
version: "1.0.0",
|
|
348
|
+
title: "AI Model Advisor",
|
|
349
|
+
description: "Which AI model is best for a given task? Uses the leaderboard to recommend.",
|
|
350
|
+
tags: RANKING_TAGS,
|
|
351
|
+
stability: "beta",
|
|
352
|
+
owners: RANKING_OWNERS
|
|
353
|
+
},
|
|
354
|
+
args: [
|
|
355
|
+
{
|
|
356
|
+
name: "task",
|
|
357
|
+
description: "The task or use case to recommend a model for.",
|
|
358
|
+
required: true,
|
|
359
|
+
schema: z.string()
|
|
360
|
+
},
|
|
361
|
+
{
|
|
362
|
+
name: "priority",
|
|
363
|
+
description: "Priority dimension (coding, reasoning, cost, latency, etc.).",
|
|
364
|
+
required: false,
|
|
365
|
+
schema: z.string().optional()
|
|
366
|
+
},
|
|
367
|
+
{
|
|
368
|
+
name: "transport",
|
|
369
|
+
description: "Required transport type (rest, mcp, webhook, sdk).",
|
|
370
|
+
required: false,
|
|
371
|
+
schema: TransportFilterSchema
|
|
372
|
+
},
|
|
373
|
+
{
|
|
374
|
+
name: "authMethod",
|
|
375
|
+
description: "Required auth method (api-key, oauth2, bearer, etc.).",
|
|
376
|
+
required: false,
|
|
377
|
+
schema: AuthFilterSchema
|
|
378
|
+
}
|
|
379
|
+
],
|
|
380
|
+
input: z.object({
|
|
381
|
+
task: z.string(),
|
|
382
|
+
priority: z.string().optional(),
|
|
383
|
+
transport: TransportFilterSchema,
|
|
384
|
+
authMethod: AuthFilterSchema
|
|
385
|
+
}),
|
|
386
|
+
render: async ({ task, priority, transport, authMethod }) => {
|
|
387
|
+
const constraints = [];
|
|
388
|
+
if (priority)
|
|
389
|
+
constraints.push(`Prioritize: ${priority}.`);
|
|
390
|
+
if (transport)
|
|
391
|
+
constraints.push(`Required transport: ${transport}.`);
|
|
392
|
+
if (authMethod)
|
|
393
|
+
constraints.push(`Required auth: ${authMethod}.`);
|
|
394
|
+
return [
|
|
395
|
+
{
|
|
396
|
+
type: "text",
|
|
397
|
+
text: `Recommend the best AI model for: "${task}".${constraints.length ? ` ${constraints.join(" ")}` : ""} Use the leaderboard data to justify your recommendation.`
|
|
398
|
+
},
|
|
399
|
+
{
|
|
400
|
+
type: "resource",
|
|
401
|
+
uri: priority ? `ranking://leaderboard/${priority}` : "ranking://leaderboard",
|
|
402
|
+
title: "Leaderboard"
|
|
403
|
+
}
|
|
404
|
+
];
|
|
405
|
+
}
|
|
406
|
+
}));
|
|
407
|
+
return prompts;
|
|
408
|
+
}
|
|
409
|
+
function buildRankingOps() {
|
|
410
|
+
const registry = new OperationSpecRegistry;
|
|
411
|
+
const ingesterRegistry = createDefaultIngesterRegistry();
|
|
412
|
+
installOp(registry, BenchmarkIngestCommand, async (args) => {
|
|
413
|
+
const store = getStore();
|
|
414
|
+
const source = args.source;
|
|
415
|
+
const ingester = ingesterRegistry.get(source);
|
|
416
|
+
if (!ingester) {
|
|
417
|
+
throw new Error(`No ingester registered for source: ${source}`);
|
|
418
|
+
}
|
|
419
|
+
const rawResults = await ingester.ingest({
|
|
420
|
+
sourceUrl: args.sourceUrl,
|
|
421
|
+
dimensions: args.dimensions
|
|
422
|
+
});
|
|
423
|
+
const normalized = normalizeBenchmarkResults(rawResults);
|
|
424
|
+
for (const result of normalized) {
|
|
425
|
+
await store.upsertBenchmarkResult(result);
|
|
426
|
+
}
|
|
427
|
+
return {
|
|
428
|
+
ingestionId: `ingest-${source}-${Date.now()}`,
|
|
429
|
+
source,
|
|
430
|
+
resultsCount: normalized.length,
|
|
431
|
+
status: "completed",
|
|
432
|
+
ingestedAt: new Date
|
|
433
|
+
};
|
|
434
|
+
});
|
|
435
|
+
installOp(registry, BenchmarkRunCustomCommand, async (args) => {
|
|
436
|
+
return {
|
|
437
|
+
runId: `custom-${Date.now()}`,
|
|
438
|
+
evalSuiteKey: args.evalSuiteKey,
|
|
439
|
+
modelId: args.modelId,
|
|
440
|
+
status: "started",
|
|
441
|
+
startedAt: new Date
|
|
442
|
+
};
|
|
443
|
+
});
|
|
444
|
+
installOp(registry, RankingRefreshCommand, async (args) => {
|
|
445
|
+
const store = getStore();
|
|
446
|
+
const allResults = [];
|
|
447
|
+
let offset = 0;
|
|
448
|
+
const pageSize = 500;
|
|
449
|
+
while (true) {
|
|
450
|
+
const page = await store.listBenchmarkResults({
|
|
451
|
+
limit: pageSize,
|
|
452
|
+
offset
|
|
453
|
+
});
|
|
454
|
+
allResults.push(...page.results);
|
|
455
|
+
if (allResults.length >= page.total || page.results.length < pageSize)
|
|
456
|
+
break;
|
|
457
|
+
offset += pageSize;
|
|
458
|
+
}
|
|
459
|
+
const existingRankings = new Map((await store.listModelRankings({ limit: 1e4 })).rankings.map((r) => [
|
|
460
|
+
r.modelId,
|
|
461
|
+
r
|
|
462
|
+
]));
|
|
463
|
+
const weightOverrides = args.weightOverrides ? Array.isArray(args.weightOverrides) ? args.weightOverrides : [args.weightOverrides] : undefined;
|
|
464
|
+
const newRankings = computeModelRankings(allResults, weightOverrides ? {
|
|
465
|
+
weightOverrides
|
|
466
|
+
} : undefined, existingRankings);
|
|
467
|
+
for (const ranking of newRankings) {
|
|
468
|
+
await store.upsertModelRanking(ranking);
|
|
469
|
+
}
|
|
470
|
+
return {
|
|
471
|
+
modelsRanked: newRankings.length,
|
|
472
|
+
updatedAt: new Date,
|
|
473
|
+
status: "completed"
|
|
474
|
+
};
|
|
475
|
+
});
|
|
476
|
+
return registry;
|
|
477
|
+
}
|
|
478
|
+
function createProviderRankingMcpHandler(path = "/api/mcp/ranking") {
|
|
479
|
+
return createMcpElysiaHandler({
|
|
480
|
+
logger: appLogger,
|
|
481
|
+
path,
|
|
482
|
+
serverName: "contractspec-ranking-mcp",
|
|
483
|
+
ops: buildRankingOps(),
|
|
484
|
+
resources: buildRankingResources(),
|
|
485
|
+
prompts: buildRankingPrompts()
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
function setProviderRankingStore(store) {
|
|
489
|
+
sharedStore = store;
|
|
490
|
+
}
|
|
491
|
+
export {
|
|
492
|
+
setProviderRankingStore,
|
|
493
|
+
createProviderRankingMcpHandler
|
|
494
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// src/application/context-storage/index.ts
|
|
2
|
+
import {
|
|
3
|
+
EmbeddingService,
|
|
4
|
+
VectorIndexer
|
|
5
|
+
} from "@contractspec/lib.knowledge/ingestion";
|
|
6
|
+
import {
|
|
7
|
+
ContextSnapshotPipeline,
|
|
8
|
+
PostgresContextStorage
|
|
9
|
+
} from "@contractspec/module.context-storage";
|
|
10
|
+
function createContextStorageService(options) {
|
|
11
|
+
const store = new PostgresContextStorage({
|
|
12
|
+
database: options.database,
|
|
13
|
+
schema: options.schema,
|
|
14
|
+
createTablesIfMissing: options.createTablesIfMissing
|
|
15
|
+
});
|
|
16
|
+
const embeddingService = options.embeddingProvider ? new EmbeddingService(options.embeddingProvider, options.embeddingBatchSize) : undefined;
|
|
17
|
+
const vectorIndexer = options.vectorStoreProvider && options.vectorIndex ? new VectorIndexer(options.vectorStoreProvider, options.vectorIndex) : undefined;
|
|
18
|
+
const pipeline = new ContextSnapshotPipeline({
|
|
19
|
+
store,
|
|
20
|
+
documentProcessor: options.documentProcessor,
|
|
21
|
+
embeddingService,
|
|
22
|
+
vectorIndexer
|
|
23
|
+
});
|
|
24
|
+
return { store, pipeline };
|
|
25
|
+
}
|
|
26
|
+
export {
|
|
27
|
+
createContextStorageService
|
|
28
|
+
};
|