@abhishek944/pi-embeddings 0.0.0-stage → 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 (51) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +87 -2
  3. package/dist/errors.d.ts +21 -0
  4. package/dist/errors.js +41 -0
  5. package/dist/execute.d.ts +25 -0
  6. package/dist/execute.js +229 -0
  7. package/dist/extension.d.ts +2 -0
  8. package/dist/extension.js +195 -0
  9. package/dist/index.d.ts +5 -0
  10. package/dist/index.js +4 -0
  11. package/dist/local-runtime.d.ts +14 -0
  12. package/dist/local-runtime.js +246 -0
  13. package/dist/mcp-cli.d.ts +2 -0
  14. package/dist/mcp-cli.js +46 -0
  15. package/dist/mcp-server.d.ts +23 -0
  16. package/dist/mcp-server.js +154 -0
  17. package/dist/provider-http.d.ts +11 -0
  18. package/dist/provider-http.js +60 -0
  19. package/dist/provider-types.d.ts +30 -0
  20. package/dist/provider-types.js +1 -0
  21. package/dist/providers.d.ts +18 -0
  22. package/dist/providers.js +265 -0
  23. package/dist/response.d.ts +11 -0
  24. package/dist/response.js +62 -0
  25. package/dist/runtime.d.ts +19 -0
  26. package/dist/runtime.js +121 -0
  27. package/dist/schemas.d.ts +431 -0
  28. package/dist/schemas.js +214 -0
  29. package/dist/settings-write.d.ts +9 -0
  30. package/dist/settings-write.js +77 -0
  31. package/dist/settings.d.ts +8 -0
  32. package/dist/settings.js +97 -0
  33. package/dist/tool-contracts.d.ts +200 -0
  34. package/dist/tool-contracts.js +19 -0
  35. package/package.json +83 -4
  36. package/src/errors.ts +52 -0
  37. package/src/execute.ts +261 -0
  38. package/src/extension.ts +245 -0
  39. package/src/index.ts +37 -0
  40. package/src/local-runtime.ts +273 -0
  41. package/src/mcp-cli.ts +52 -0
  42. package/src/mcp-server.ts +206 -0
  43. package/src/provider-http.ts +67 -0
  44. package/src/provider-types.ts +33 -0
  45. package/src/providers.ts +335 -0
  46. package/src/response.ts +74 -0
  47. package/src/runtime.ts +146 -0
  48. package/src/schemas.ts +326 -0
  49. package/src/settings-write.ts +96 -0
  50. package/src/settings.ts +115 -0
  51. package/src/tool-contracts.ts +34 -0
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Package-owned pinned CPU EmbeddingGemma 2 runtime.
3
+ *
4
+ * The operator supplies compatible assets through package settings. Nothing is downloaded, installed,
5
+ * discovered globally, inherited from a provider or borrowed from a foreign listener.
6
+ */
7
+ import { spawn, execFile, type ChildProcess } from 'node:child_process';
8
+ import { createHash } from 'node:crypto';
9
+ import { constants } from 'node:fs';
10
+ import { createReadStream } from 'node:fs';
11
+ import { access } from 'node:fs/promises';
12
+ import { createInterface } from 'node:readline';
13
+ import { promisify } from 'node:util';
14
+ import { Type } from 'typebox';
15
+ import { Value } from 'typebox/value';
16
+ import { EmbeddingsError } from './errors.js';
17
+ import { requestJson } from './provider-http.js';
18
+ import type { EmbeddingsProvider, PreparedInput, ProviderBatchResult } from './provider-types.js';
19
+ import { parseBatchResponse } from './response.js';
20
+ import {
21
+ EMBEDDING_DOCUMENT_PREFIX,
22
+ EMBEDDING_FORMAT_VERSION,
23
+ EMBEDDING_NORMALIZATION_VERSION,
24
+ type EmbeddingSpace,
25
+ } from './schemas.js';
26
+
27
+ const MODEL_SHA256 = '2188ac1deca4b77dffefd603c2776a9d76d9d74ec01841392982ebb840b09135';
28
+ const RUNTIME_COMMIT = 'af6b5243d6871923dfecbe06814bd566d9dc383b';
29
+ const DEFAULT_PORT = 8791;
30
+
31
+ export type LocalRuntimeConfig = Readonly<{
32
+ executable: string;
33
+ modelPath: string;
34
+ port: number;
35
+ }>;
36
+
37
+ const tokenResponseSchema = Type.Object({
38
+ tokens: Type.Array(Type.Integer({ minimum: 0 }), { minItems: 1 }),
39
+ });
40
+
41
+ export const LOCAL_EMBEDDING_SPACE: EmbeddingSpace = Object.freeze({
42
+ provider: 'local',
43
+ model: 'embeddinggemma-2',
44
+ revision: `6ea3e3a309d12a4779cfda98b8c19800d2d5da71:sha256:${MODEL_SHA256}`,
45
+ quantization: 'Q8_0',
46
+ runtime: `llama.cpp:${RUNTIME_COMMIT}:mean`,
47
+ dimensions: 768,
48
+ format: EMBEDDING_FORMAT_VERSION,
49
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
50
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
51
+ });
52
+
53
+ class LocalRuntimeProvider implements EmbeddingsProvider {
54
+ readonly route = 'local' as const;
55
+ readonly model = 'embeddinggemma-2';
56
+ readonly space: EmbeddingSpace = LOCAL_EMBEDDING_SPACE;
57
+ readonly maxRequestInputs = Number.POSITIVE_INFINITY;
58
+ readonly maxRequestTokens = Number.POSITIVE_INFINITY;
59
+ readonly #origin: URL;
60
+ readonly #process: ChildProcess;
61
+ readonly #closed: Promise<void>;
62
+ #closeStarted = false;
63
+
64
+ private constructor(child: ChildProcess, port: number, closed: Promise<void>) {
65
+ this.#process = child;
66
+ this.#origin = new URL(`http://127.0.0.1:${port}`);
67
+ this.#closed = closed;
68
+ }
69
+
70
+ static async open(config: LocalRuntimeConfig, signal: AbortSignal): Promise<LocalRuntimeProvider> {
71
+ const environment = { PATH: process.env.PATH, HOME: process.env.HOME };
72
+ try {
73
+ await access(config.executable, constants.X_OK);
74
+ const digest = createHash('sha256');
75
+ for await (const chunk of createReadStream(config.modelPath, { signal }))
76
+ digest.update(chunk);
77
+ if (digest.digest('hex') !== MODEL_SHA256) throw new EmbeddingsError('local-model-mismatch');
78
+ const version = await promisify(execFile)(config.executable, ['--version'], {
79
+ signal,
80
+ env: environment,
81
+ });
82
+ if (!(version.stdout + version.stderr).includes('af6b5243'))
83
+ throw new EmbeddingsError('local-runtime-mismatch');
84
+ } catch (error) {
85
+ if (error instanceof EmbeddingsError) throw error;
86
+ if (signal.aborted) throw new EmbeddingsError('cancelled');
87
+ throw new EmbeddingsError('local-resources-unavailable');
88
+ }
89
+ signal.throwIfAborted();
90
+ const child = spawn(
91
+ config.executable,
92
+ [
93
+ '--model', config.modelPath,
94
+ '--alias', 'embeddinggemma-2',
95
+ '--offline',
96
+ '--embedding',
97
+ '--pooling', 'mean',
98
+ '--embd-normalize', '2',
99
+ '--ctx-size', '8192',
100
+ '--parallel', '1',
101
+ '--batch-size', '8192',
102
+ '--ubatch-size', '8192',
103
+ '--gpu-layers', '0',
104
+ '--device', 'none',
105
+ '--no-op-offload',
106
+ '--no-kv-offload',
107
+ '--no-cache-prompt',
108
+ '--host', '127.0.0.1',
109
+ '--port', String(config.port),
110
+ '--no-webui',
111
+ '--no-warmup',
112
+ '--log-colors', 'off',
113
+ '--verbosity', '4',
114
+ ],
115
+ { env: environment, stdio: ['ignore', 'pipe', 'pipe'] }
116
+ );
117
+ const closed = new Promise<void>((resolve) => child.once('close', () => resolve()));
118
+ const provider = new LocalRuntimeProvider(child, config.port, closed);
119
+ const abort = (): void => {
120
+ child.kill('SIGTERM');
121
+ };
122
+ signal.addEventListener('abort', abort, { once: true });
123
+ try {
124
+ await new Promise<void>((resolve, reject) => {
125
+ let cpuBuffer = false;
126
+ let gpuBuffer = false;
127
+ const observe = (line: string): void => {
128
+ cpuBuffer ||= /CPU[^\n]*model buffer|model buffer[^\n]*CPU/iu.test(line);
129
+ gpuBuffer ||=
130
+ /(Metal|MTL\d|CUDA|Vulkan)[^\n]*(model|compute|KV).*buffer size|offloaded\s+[1-9]\d*\//iu.test(
131
+ line
132
+ );
133
+ if (line.includes('listening on http://127.0.0.1:')) {
134
+ if (cpuBuffer && !gpuBuffer && !signal.aborted) resolve();
135
+ else reject(new EmbeddingsError('local-cpu-startup-invalid'));
136
+ }
137
+ };
138
+ if (child.stdout) createInterface({ input: child.stdout }).on('line', observe);
139
+ if (child.stderr) createInterface({ input: child.stderr }).on('line', observe);
140
+ child.once('error', () => reject(new EmbeddingsError('local-startup-failed')));
141
+ child.once('close', () => reject(new EmbeddingsError('local-startup-failed')));
142
+ });
143
+ const health = await fetch(new URL('/health', provider.#origin), { signal, redirect: 'error' });
144
+ if (!health.ok) throw new EmbeddingsError('local-startup-failed');
145
+ return provider;
146
+ } catch (error) {
147
+ await provider.close();
148
+ throw error;
149
+ } finally {
150
+ signal.removeEventListener('abort', abort);
151
+ }
152
+ }
153
+
154
+ async prepare(text: string, signal: AbortSignal): Promise<PreparedInput> {
155
+ const response = await requestJson({
156
+ url: new URL('/tokenize', this.#origin),
157
+ body: { content: EMBEDDING_DOCUMENT_PREFIX + text, add_special: true, parse_special: false },
158
+ signal,
159
+ });
160
+ if (!Value.Check(tokenResponseSchema, response))
161
+ throw new EmbeddingsError('provider-response-invalid');
162
+ if (response.tokens.length > 8192) throw new EmbeddingsError('input-too-long');
163
+ return { kind: 'tokens', tokens: response.tokens };
164
+ }
165
+
166
+ async embed(inputs: readonly PreparedInput[], signal: AbortSignal): Promise<ProviderBatchResult> {
167
+ const tokens = inputs.map((input) => {
168
+ if (input.kind !== 'tokens') throw new EmbeddingsError('provider-response-invalid');
169
+ return input.tokens;
170
+ });
171
+ const response = await requestJson({
172
+ url: new URL('/v1/embeddings', this.#origin),
173
+ body: { model: this.model, input: tokens, encoding_format: 'float' },
174
+ signal,
175
+ });
176
+ const prepared = tokens.reduce((sum, item) => sum + item.length, 0);
177
+ return parseBatchResponse({
178
+ response,
179
+ space: this.space,
180
+ expectedPreparedTokens: prepared,
181
+ preparedInputTokens: prepared,
182
+ });
183
+ }
184
+
185
+ async close(): Promise<void> {
186
+ if (this.#closeStarted) return;
187
+ this.#closeStarted = true;
188
+ if (this.#process.exitCode === null && this.#process.signalCode === null)
189
+ this.#process.kill('SIGTERM');
190
+ await this.#closed;
191
+ }
192
+ }
193
+
194
+ type Entry = {
195
+ readonly key: string;
196
+ readonly controller: AbortController;
197
+ readonly promise: Promise<EmbeddingsProvider>;
198
+ refs: number;
199
+ closing: Promise<void> | null;
200
+ };
201
+
202
+ const entries = new Map<string, Entry>();
203
+
204
+ const waitFor = (promise: Promise<EmbeddingsProvider>, signal: AbortSignal): Promise<EmbeddingsProvider> => {
205
+ if (signal.aborted) return Promise.reject(new EmbeddingsError('cancelled'));
206
+ let listener: (() => void) | undefined;
207
+ const cancelled = new Promise<never>((_resolve, reject) => {
208
+ listener = () => reject(new EmbeddingsError('cancelled'));
209
+ signal.addEventListener('abort', listener, { once: true });
210
+ });
211
+ return Promise.race([promise, cancelled]).finally(() => {
212
+ if (listener !== undefined) signal.removeEventListener('abort', listener);
213
+ });
214
+ };
215
+
216
+ export type AcquiredLocalRuntime = Readonly<{
217
+ readonly provider: EmbeddingsProvider;
218
+ readonly release: () => Promise<void>;
219
+ }>;
220
+
221
+ /** One owned child per pinned configuration, shared across all runtimes that resolve it. */
222
+ export async function acquireLocalRuntime(
223
+ config: LocalRuntimeConfig,
224
+ signal: AbortSignal
225
+ ): Promise<AcquiredLocalRuntime> {
226
+ signal.throwIfAborted();
227
+ const normalized: LocalRuntimeConfig = {
228
+ executable: config.executable,
229
+ modelPath: config.modelPath,
230
+ port: config.port || DEFAULT_PORT,
231
+ };
232
+ const key = JSON.stringify(normalized);
233
+ let entry = entries.get(key);
234
+ while (entry !== undefined && entry.closing !== null) {
235
+ await entry.closing;
236
+ entry = entries.get(key);
237
+ }
238
+ if (entry === undefined) {
239
+ const controller = new AbortController();
240
+ const promise = LocalRuntimeProvider.open(normalized, controller.signal).catch(
241
+ (error: unknown) => {
242
+ if (entries.get(key)?.controller === controller) entries.delete(key);
243
+ throw error;
244
+ }
245
+ );
246
+ entry = { key, controller, promise, refs: 0, closing: null };
247
+ entries.set(key, entry);
248
+ }
249
+ const acquired = entry;
250
+ acquired.refs += 1;
251
+ let released = false;
252
+ const release = async (): Promise<void> => {
253
+ if (released) return;
254
+ released = true;
255
+ acquired.refs -= 1;
256
+ if (acquired.refs > 0) return;
257
+ if (acquired.closing === null)
258
+ acquired.closing = (async () => {
259
+ acquired.controller.abort();
260
+ const provider = await acquired.promise.catch(() => undefined);
261
+ await provider?.close();
262
+ })().finally(() => {
263
+ if (entries.get(acquired.key) === acquired) entries.delete(acquired.key);
264
+ });
265
+ await acquired.closing;
266
+ };
267
+ try {
268
+ return { provider: await waitFor(acquired.promise, signal), release };
269
+ } catch (error) {
270
+ await release();
271
+ throw error;
272
+ }
273
+ }
package/src/mcp-cli.ts ADDED
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+ // pi-embeddings-mcp: JSON-RPC only on stdout; all diagnostics go to stderr.
3
+
4
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5
+ import { createEmbeddingsRuntime } from './runtime.js';
6
+ import { loadEmbeddingSettings } from './settings.js';
7
+ import { createEmbeddingsMcpServer } from './mcp-server.js';
8
+ import type { EmbeddingsRuntime } from './runtime.js';
9
+
10
+ console.log = console.info = console.debug = console.error;
11
+
12
+ let closing = false;
13
+ let server: Awaited<ReturnType<typeof createEmbeddingsMcpServer>> | undefined;
14
+ let runtime: EmbeddingsRuntime | undefined;
15
+
16
+ const shutdown = async (code: number): Promise<void> => {
17
+ if (closing) return;
18
+ closing = true;
19
+ try {
20
+ await server?.close();
21
+ } catch (error) {
22
+ console.error('pi-embeddings-mcp: server close failed:', error instanceof Error ? error.message : 'unknown');
23
+ }
24
+ try {
25
+ await runtime?.close();
26
+ } catch (error) {
27
+ console.error('pi-embeddings-mcp: runtime close failed:', error instanceof Error ? error.message : 'unknown');
28
+ }
29
+ process.exit(code);
30
+ };
31
+
32
+ process.stdin.once('end', () => void shutdown(0));
33
+ process.stdin.once('close', () => void shutdown(0));
34
+ process.once('SIGINT', () => void shutdown(0));
35
+ process.once('SIGTERM', () => void shutdown(0));
36
+
37
+ try {
38
+ const cwd = process.cwd();
39
+ runtime = createEmbeddingsRuntime({
40
+ settings: loadEmbeddingSettings(cwd, false),
41
+ cwd,
42
+ });
43
+ server = await createEmbeddingsMcpServer({ cwd, runtime });
44
+ await server.connect(new StdioServerTransport());
45
+ } catch (error) {
46
+ console.error(
47
+ 'pi-embeddings-mcp: failed to start:',
48
+ error instanceof Error ? error.message : 'unknown'
49
+ );
50
+ await runtime?.close().catch(() => undefined);
51
+ process.exit(1);
52
+ }
@@ -0,0 +1,206 @@
1
+ import { createRequire } from 'node:module';
2
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
+ import {
4
+ CallToolRequestSchema,
5
+ ErrorCode,
6
+ ListToolsRequestSchema,
7
+ McpError,
8
+ type CallToolResult,
9
+ } from '@modelcontextprotocol/sdk/types.js';
10
+ import type { TSchema } from 'typebox';
11
+ import { Value } from 'typebox/value';
12
+ import { EmbeddingsError } from './errors.js';
13
+ import { createEmbeddingsRuntime, type EmbeddingsRuntime } from './runtime.js';
14
+ import { loadEmbeddingSettings } from './settings.js';
15
+ import {
16
+ EMBEDDING_CONTEXT_META_KEY,
17
+ embeddingContextSchema,
18
+ embeddingRequestSchema,
19
+ type EmbeddingContext,
20
+ type EmbeddingRequest,
21
+ type EmbeddingSettings,
22
+ } from './schemas.js';
23
+ import {
24
+ EMBED_COMPARE_TOOL,
25
+ EMBED_TOOL,
26
+ EMBEDDINGS_DESCRIBE_TOOL,
27
+ EMBED_COMPARE_TOOL_DESCRIPTION,
28
+ EMBED_TOOL_DESCRIPTION,
29
+ EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION,
30
+ embedCompareParameters,
31
+ embedParameters,
32
+ embeddingsDescribeParameters,
33
+ } from './tool-contracts.js';
34
+
35
+ const require = createRequire(import.meta.url);
36
+ const manifest: unknown = require('../package.json');
37
+ const version =
38
+ typeof manifest === 'object' && manifest !== null && 'version' in manifest && typeof manifest.version === 'string'
39
+ ? manifest.version
40
+ : '0.0.0';
41
+
42
+ export const embeddingsMcpServerInfo = { name: 'pi-embeddings', version };
43
+
44
+ export interface EmbeddingsMcpServerOptions {
45
+ cwd?: string | undefined;
46
+ settings?: EmbeddingSettings;
47
+ /** Project settings are never read unless the host explicitly asserts trust. */
48
+ projectTrusted?: boolean;
49
+ runtime?: EmbeddingsRuntime;
50
+ info?: { name: string; version: string };
51
+ }
52
+
53
+ const errorResult = (text: string): CallToolResult => ({
54
+ content: [{ type: 'text', text }],
55
+ isError: true,
56
+ });
57
+
58
+ const jsonResult = (value: object, text: string): CallToolResult => ({
59
+ content: [{ type: 'text', text }],
60
+ structuredContent: { result: value },
61
+ });
62
+
63
+ const isRequest = (value: unknown): value is EmbeddingRequest =>
64
+ Value.Check(embeddingRequestSchema, value);
65
+
66
+ const validationProblems = (schema: TSchema, args: unknown): string[] => {
67
+ if (Value.Check(schema, args)) return [];
68
+ const problems = new Set<string>();
69
+ for (const issue of Value.Errors(schema, args)) {
70
+ if (issue.keyword === 'boolean') continue;
71
+ const path = issue.instancePath === '' ? 'arguments' : issue.instancePath;
72
+ const extra = (issue.params as { additionalProperties?: string[] }).additionalProperties;
73
+ problems.add(
74
+ extra === undefined
75
+ ? `${path}: ${issue.message ?? 'invalid value'}`
76
+ : `${path}: unknown or server-owned properties ${extra.join(', ')}`
77
+ );
78
+ }
79
+ return [...problems];
80
+ };
81
+
82
+ /** Trusted host attribution is read only from namespaced MCP metadata, never from model arguments. */
83
+ function readContext(request: unknown): EmbeddingContext | undefined {
84
+ if (typeof request !== 'object' || request === null || !('params' in request))
85
+ throw new EmbeddingsError('configuration-invalid');
86
+ const requestParams = (request as { params: unknown }).params;
87
+ if (typeof requestParams !== 'object' || requestParams === null)
88
+ throw new EmbeddingsError('configuration-invalid');
89
+ const params: Record<string, unknown> = { ...requestParams };
90
+ const meta = params['_meta'];
91
+ if (meta === undefined) return undefined;
92
+ if (typeof meta !== 'object' || meta === null || Array.isArray(meta))
93
+ throw new EmbeddingsError('configuration-invalid');
94
+ const namespaced = (meta as Record<string, unknown>)[EMBEDDING_CONTEXT_META_KEY];
95
+ if (namespaced === undefined) return undefined;
96
+ if (!Value.Check(embeddingContextSchema, namespaced))
97
+ throw new EmbeddingsError('configuration-invalid');
98
+ return namespaced;
99
+ }
100
+
101
+ const summary = (result: {
102
+ outcomes: readonly { readonly status: string; readonly route?: string; readonly model?: string }[];
103
+ }): string => {
104
+ const successes = result.outcomes.filter((outcome) => outcome.status === 'success');
105
+ const errors = result.outcomes.length - successes.length;
106
+ const routes = [
107
+ ...new Set(successes.map((outcome) => `${outcome.route}:${outcome.model}`)),
108
+ ].join(', ');
109
+ return `Embedded ${successes.length}/${result.outcomes.length} input(s)${routes === '' ? '' : ` via ${routes}`}${errors === 0 ? '' : `; ${errors} failed`}.`;
110
+ };
111
+
112
+ /**
113
+ * Create one MCP server around a package-owned runtime. The caller owns transport, the returned
114
+ * server, and runtime shutdown; closing a session never closes the shared runtime.
115
+ */
116
+ export async function createEmbeddingsMcpServer(
117
+ options: EmbeddingsMcpServerOptions = {}
118
+ ): Promise<Server> {
119
+ const ownsRuntime = options.runtime === undefined;
120
+ const runtime =
121
+ options.runtime ??
122
+ createEmbeddingsRuntime({
123
+ settings: options.settings ?? loadEmbeddingSettings(options.cwd ?? process.cwd(), options.projectTrusted ?? false),
124
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
125
+ });
126
+ await runtime.start();
127
+
128
+ const server = new Server(options.info ?? embeddingsMcpServerInfo, {
129
+ capabilities: { tools: {} },
130
+ instructions:
131
+ 'Independent pi-embeddings MCP server. Provider, model and credentials stay on the server and cannot be overridden by tool arguments. Vectors are returned in structuredContent.result. Comparison runs only on explicit request and may incur multiple charges.',
132
+ });
133
+
134
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
135
+ tools: [
136
+ {
137
+ name: EMBED_TOOL,
138
+ description: EMBED_TOOL_DESCRIPTION,
139
+ inputSchema: embedParameters,
140
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
141
+ },
142
+ {
143
+ name: EMBED_COMPARE_TOOL,
144
+ description: EMBED_COMPARE_TOOL_DESCRIPTION,
145
+ inputSchema: embedCompareParameters,
146
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
147
+ },
148
+ {
149
+ name: EMBEDDINGS_DESCRIBE_TOOL,
150
+ description: EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION,
151
+ inputSchema: embeddingsDescribeParameters,
152
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
153
+ },
154
+ ],
155
+ }));
156
+
157
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
158
+ const args = request.params.arguments ?? {};
159
+ try {
160
+ switch (request.params.name) {
161
+ case EMBED_TOOL:
162
+ case EMBED_COMPARE_TOOL: {
163
+ const problems = validationProblems(embeddingRequestSchema, args);
164
+ if (problems.length > 0)
165
+ return errorResult(`Invalid arguments for ${request.params.name}:\n- ${problems.join('\n- ')}`);
166
+ if (!isRequest(args)) return errorResult('Invalid embedding request.');
167
+ const context = readContext(request);
168
+ if (request.params.name === EMBED_TOOL) {
169
+ const result = await runtime.embed(args, { signal: extra.signal, context });
170
+ return jsonResult(result, summary(result));
171
+ }
172
+ const compared = await runtime.compare(args, { signal: extra.signal, context });
173
+ return jsonResult(compared, `Compared ${compared.entries.length} configured embedding route(s).`);
174
+ }
175
+ case EMBEDDINGS_DESCRIBE_TOOL: {
176
+ const problems = validationProblems(embeddingsDescribeParameters, args);
177
+ if (problems.length > 0)
178
+ return errorResult(`Invalid arguments for ${request.params.name}:\n- ${problems.join('\n- ')}`);
179
+ const described = runtime.describe();
180
+ return jsonResult(
181
+ described,
182
+ `Embedding route ${described.selected.provider}/${described.selected.model}; ready: ${described.ready}.`
183
+ );
184
+ }
185
+ default:
186
+ throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${request.params.name}`);
187
+ }
188
+ } catch (error) {
189
+ const code = error instanceof EmbeddingsError ? error.code : 'configuration-invalid';
190
+ return errorResult(`${request.params.name} failed: ${code}`);
191
+ }
192
+ });
193
+
194
+ if (ownsRuntime) {
195
+ let ownClosed = false;
196
+ const closeServer = server.close.bind(server);
197
+ const wrapped = server as Server & { close: () => Promise<void> };
198
+ wrapped.close = async () => {
199
+ if (ownClosed) return;
200
+ ownClosed = true;
201
+ await closeServer();
202
+ await runtime.close();
203
+ };
204
+ }
205
+ return server;
206
+ }
@@ -0,0 +1,67 @@
1
+ import { EmbeddingsError, statusCode } from './errors.js';
2
+
3
+ /** Native fetch with fixed URLs, no retries and no response bodies in diagnostics. */
4
+ export async function requestJson(args: {
5
+ url: URL;
6
+ body: unknown;
7
+ signal: AbortSignal;
8
+ headers?: Readonly<Record<string, string>>;
9
+ }): Promise<unknown> {
10
+ let response: Response;
11
+ try {
12
+ response = await fetch(args.url, {
13
+ method: 'POST',
14
+ headers: {
15
+ 'content-type': 'application/json',
16
+ accept: 'application/json',
17
+ ...args.headers,
18
+ },
19
+ body: JSON.stringify(args.body),
20
+ signal: args.signal,
21
+ redirect: 'error',
22
+ });
23
+ } catch (error) {
24
+ if (args.signal.aborted) throw new EmbeddingsError('cancelled');
25
+ void error;
26
+ throw new EmbeddingsError('transport-failed');
27
+ }
28
+ if (!response.ok) {
29
+ const code = statusCode(response.status);
30
+ throw new EmbeddingsError(code, { httpStatus: response.status });
31
+ }
32
+ try {
33
+ return (await response.json()) as unknown;
34
+ } catch {
35
+ throw new EmbeddingsError('provider-response-invalid');
36
+ }
37
+ }
38
+
39
+ /** Fixed origins only; project settings cannot introduce an arbitrary provider endpoint. */
40
+ export const fixedOrigin = (raw: string): URL => {
41
+ let url: URL;
42
+ try {
43
+ url = new URL(raw);
44
+ } catch {
45
+ throw new EmbeddingsError('configuration-invalid');
46
+ }
47
+ const loopback = url.hostname === 'localhost' || url.hostname === '127.0.0.1';
48
+ if (
49
+ (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) ||
50
+ url.username !== '' ||
51
+ url.password !== '' ||
52
+ url.search !== '' ||
53
+ url.hash !== ''
54
+ )
55
+ throw new EmbeddingsError('configuration-invalid');
56
+ url.pathname = '';
57
+ url.search = '';
58
+ url.hash = '';
59
+ return url;
60
+ };
61
+
62
+ /** One-line header values with no control characters are the only labels this package forwards. */
63
+ export const headerValueIsSafe = (value: string): boolean =>
64
+ value.length > 0 && [...value].every((character) => {
65
+ const code = character.codePointAt(0) ?? 0;
66
+ return code >= 0x20 && code !== 0x7f;
67
+ });
@@ -0,0 +1,33 @@
1
+ import type { EmbeddingContext, EmbeddingRouteId, EmbeddingSpace } from './schemas.js';
2
+
3
+ /** The prepared form is provider-owned and never exposed as a model-facing caller input. */
4
+ export type PreparedInput =
5
+ | Readonly<{ readonly kind: 'text'; readonly text: string; readonly tokenCount: number | null }>
6
+ | Readonly<{ readonly kind: 'tokens'; readonly tokens: readonly number[] }>;
7
+
8
+ export type ProviderUsage = Readonly<{
9
+ readonly providerReportedInputTokens: number | null;
10
+ readonly preparedInputTokens: number | null;
11
+ readonly billedTokens: number | null;
12
+ }>;
13
+
14
+ export type ProviderBatchResult = Readonly<{
15
+ readonly vectors: readonly (readonly number[])[];
16
+ readonly usage: ProviderUsage;
17
+ }>;
18
+
19
+ export interface EmbeddingsProvider {
20
+ readonly route: EmbeddingRouteId;
21
+ readonly model: string;
22
+ readonly space: EmbeddingSpace;
23
+ /** Mandatory provider request boundaries. Infinity means no declared request-level ceiling. */
24
+ readonly maxRequestInputs: number;
25
+ readonly maxRequestTokens: number;
26
+ prepare(text: string, signal: AbortSignal): Promise<PreparedInput>;
27
+ embed(
28
+ inputs: readonly PreparedInput[],
29
+ signal: AbortSignal,
30
+ context: EmbeddingContext | undefined
31
+ ): Promise<ProviderBatchResult>;
32
+ close(): Promise<void>;
33
+ }