@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,154 @@
1
+ import { createRequire } from 'node:module';
2
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
+ import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError, } from '@modelcontextprotocol/sdk/types.js';
4
+ import { Value } from 'typebox/value';
5
+ import { EmbeddingsError } from './errors.js';
6
+ import { createEmbeddingsRuntime } from './runtime.js';
7
+ import { loadEmbeddingSettings } from './settings.js';
8
+ import { EMBEDDING_CONTEXT_META_KEY, embeddingContextSchema, embeddingRequestSchema, } from './schemas.js';
9
+ import { EMBED_COMPARE_TOOL, EMBED_TOOL, EMBEDDINGS_DESCRIBE_TOOL, EMBED_COMPARE_TOOL_DESCRIPTION, EMBED_TOOL_DESCRIPTION, EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION, embedCompareParameters, embedParameters, embeddingsDescribeParameters, } from './tool-contracts.js';
10
+ const require = createRequire(import.meta.url);
11
+ const manifest = require('../package.json');
12
+ const version = typeof manifest === 'object' && manifest !== null && 'version' in manifest && typeof manifest.version === 'string'
13
+ ? manifest.version
14
+ : '0.0.0';
15
+ export const embeddingsMcpServerInfo = { name: 'pi-embeddings', version };
16
+ const errorResult = (text) => ({
17
+ content: [{ type: 'text', text }],
18
+ isError: true,
19
+ });
20
+ const jsonResult = (value, text) => ({
21
+ content: [{ type: 'text', text }],
22
+ structuredContent: { result: value },
23
+ });
24
+ const isRequest = (value) => Value.Check(embeddingRequestSchema, value);
25
+ const validationProblems = (schema, args) => {
26
+ if (Value.Check(schema, args))
27
+ return [];
28
+ const problems = new Set();
29
+ for (const issue of Value.Errors(schema, args)) {
30
+ if (issue.keyword === 'boolean')
31
+ continue;
32
+ const path = issue.instancePath === '' ? 'arguments' : issue.instancePath;
33
+ const extra = issue.params.additionalProperties;
34
+ problems.add(extra === undefined
35
+ ? `${path}: ${issue.message ?? 'invalid value'}`
36
+ : `${path}: unknown or server-owned properties ${extra.join(', ')}`);
37
+ }
38
+ return [...problems];
39
+ };
40
+ /** Trusted host attribution is read only from namespaced MCP metadata, never from model arguments. */
41
+ function readContext(request) {
42
+ if (typeof request !== 'object' || request === null || !('params' in request))
43
+ throw new EmbeddingsError('configuration-invalid');
44
+ const requestParams = request.params;
45
+ if (typeof requestParams !== 'object' || requestParams === null)
46
+ throw new EmbeddingsError('configuration-invalid');
47
+ const params = { ...requestParams };
48
+ const meta = params['_meta'];
49
+ if (meta === undefined)
50
+ return undefined;
51
+ if (typeof meta !== 'object' || meta === null || Array.isArray(meta))
52
+ throw new EmbeddingsError('configuration-invalid');
53
+ const namespaced = meta[EMBEDDING_CONTEXT_META_KEY];
54
+ if (namespaced === undefined)
55
+ return undefined;
56
+ if (!Value.Check(embeddingContextSchema, namespaced))
57
+ throw new EmbeddingsError('configuration-invalid');
58
+ return namespaced;
59
+ }
60
+ const summary = (result) => {
61
+ const successes = result.outcomes.filter((outcome) => outcome.status === 'success');
62
+ const errors = result.outcomes.length - successes.length;
63
+ const routes = [
64
+ ...new Set(successes.map((outcome) => `${outcome.route}:${outcome.model}`)),
65
+ ].join(', ');
66
+ return `Embedded ${successes.length}/${result.outcomes.length} input(s)${routes === '' ? '' : ` via ${routes}`}${errors === 0 ? '' : `; ${errors} failed`}.`;
67
+ };
68
+ /**
69
+ * Create one MCP server around a package-owned runtime. The caller owns transport, the returned
70
+ * server, and runtime shutdown; closing a session never closes the shared runtime.
71
+ */
72
+ export async function createEmbeddingsMcpServer(options = {}) {
73
+ const ownsRuntime = options.runtime === undefined;
74
+ const runtime = options.runtime ??
75
+ createEmbeddingsRuntime({
76
+ settings: options.settings ?? loadEmbeddingSettings(options.cwd ?? process.cwd(), options.projectTrusted ?? false),
77
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
78
+ });
79
+ await runtime.start();
80
+ const server = new Server(options.info ?? embeddingsMcpServerInfo, {
81
+ capabilities: { tools: {} },
82
+ instructions: '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.',
83
+ });
84
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
85
+ tools: [
86
+ {
87
+ name: EMBED_TOOL,
88
+ description: EMBED_TOOL_DESCRIPTION,
89
+ inputSchema: embedParameters,
90
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
91
+ },
92
+ {
93
+ name: EMBED_COMPARE_TOOL,
94
+ description: EMBED_COMPARE_TOOL_DESCRIPTION,
95
+ inputSchema: embedCompareParameters,
96
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
97
+ },
98
+ {
99
+ name: EMBEDDINGS_DESCRIBE_TOOL,
100
+ description: EMBEDDINGS_DESCRIBE_TOOL_DESCRIPTION,
101
+ inputSchema: embeddingsDescribeParameters,
102
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
103
+ },
104
+ ],
105
+ }));
106
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
107
+ const args = request.params.arguments ?? {};
108
+ try {
109
+ switch (request.params.name) {
110
+ case EMBED_TOOL:
111
+ case EMBED_COMPARE_TOOL: {
112
+ const problems = validationProblems(embeddingRequestSchema, args);
113
+ if (problems.length > 0)
114
+ return errorResult(`Invalid arguments for ${request.params.name}:\n- ${problems.join('\n- ')}`);
115
+ if (!isRequest(args))
116
+ return errorResult('Invalid embedding request.');
117
+ const context = readContext(request);
118
+ if (request.params.name === EMBED_TOOL) {
119
+ const result = await runtime.embed(args, { signal: extra.signal, context });
120
+ return jsonResult(result, summary(result));
121
+ }
122
+ const compared = await runtime.compare(args, { signal: extra.signal, context });
123
+ return jsonResult(compared, `Compared ${compared.entries.length} configured embedding route(s).`);
124
+ }
125
+ case EMBEDDINGS_DESCRIBE_TOOL: {
126
+ const problems = validationProblems(embeddingsDescribeParameters, args);
127
+ if (problems.length > 0)
128
+ return errorResult(`Invalid arguments for ${request.params.name}:\n- ${problems.join('\n- ')}`);
129
+ const described = runtime.describe();
130
+ return jsonResult(described, `Embedding route ${described.selected.provider}/${described.selected.model}; ready: ${described.ready}.`);
131
+ }
132
+ default:
133
+ throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${request.params.name}`);
134
+ }
135
+ }
136
+ catch (error) {
137
+ const code = error instanceof EmbeddingsError ? error.code : 'configuration-invalid';
138
+ return errorResult(`${request.params.name} failed: ${code}`);
139
+ }
140
+ });
141
+ if (ownsRuntime) {
142
+ let ownClosed = false;
143
+ const closeServer = server.close.bind(server);
144
+ const wrapped = server;
145
+ wrapped.close = async () => {
146
+ if (ownClosed)
147
+ return;
148
+ ownClosed = true;
149
+ await closeServer();
150
+ await runtime.close();
151
+ };
152
+ }
153
+ return server;
154
+ }
@@ -0,0 +1,11 @@
1
+ /** Native fetch with fixed URLs, no retries and no response bodies in diagnostics. */
2
+ export declare function requestJson(args: {
3
+ url: URL;
4
+ body: unknown;
5
+ signal: AbortSignal;
6
+ headers?: Readonly<Record<string, string>>;
7
+ }): Promise<unknown>;
8
+ /** Fixed origins only; project settings cannot introduce an arbitrary provider endpoint. */
9
+ export declare const fixedOrigin: (raw: string) => URL;
10
+ /** One-line header values with no control characters are the only labels this package forwards. */
11
+ export declare const headerValueIsSafe: (value: string) => boolean;
@@ -0,0 +1,60 @@
1
+ import { EmbeddingsError, statusCode } from './errors.js';
2
+ /** Native fetch with fixed URLs, no retries and no response bodies in diagnostics. */
3
+ export async function requestJson(args) {
4
+ let response;
5
+ try {
6
+ response = await fetch(args.url, {
7
+ method: 'POST',
8
+ headers: {
9
+ 'content-type': 'application/json',
10
+ accept: 'application/json',
11
+ ...args.headers,
12
+ },
13
+ body: JSON.stringify(args.body),
14
+ signal: args.signal,
15
+ redirect: 'error',
16
+ });
17
+ }
18
+ catch (error) {
19
+ if (args.signal.aborted)
20
+ throw new EmbeddingsError('cancelled');
21
+ void error;
22
+ throw new EmbeddingsError('transport-failed');
23
+ }
24
+ if (!response.ok) {
25
+ const code = statusCode(response.status);
26
+ throw new EmbeddingsError(code, { httpStatus: response.status });
27
+ }
28
+ try {
29
+ return (await response.json());
30
+ }
31
+ catch {
32
+ throw new EmbeddingsError('provider-response-invalid');
33
+ }
34
+ }
35
+ /** Fixed origins only; project settings cannot introduce an arbitrary provider endpoint. */
36
+ export const fixedOrigin = (raw) => {
37
+ let url;
38
+ try {
39
+ url = new URL(raw);
40
+ }
41
+ catch {
42
+ throw new EmbeddingsError('configuration-invalid');
43
+ }
44
+ const loopback = url.hostname === 'localhost' || url.hostname === '127.0.0.1';
45
+ if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) ||
46
+ url.username !== '' ||
47
+ url.password !== '' ||
48
+ url.search !== '' ||
49
+ url.hash !== '')
50
+ throw new EmbeddingsError('configuration-invalid');
51
+ url.pathname = '';
52
+ url.search = '';
53
+ url.hash = '';
54
+ return url;
55
+ };
56
+ /** One-line header values with no control characters are the only labels this package forwards. */
57
+ export const headerValueIsSafe = (value) => value.length > 0 && [...value].every((character) => {
58
+ const code = character.codePointAt(0) ?? 0;
59
+ return code >= 0x20 && code !== 0x7f;
60
+ });
@@ -0,0 +1,30 @@
1
+ import type { EmbeddingContext, EmbeddingRouteId, EmbeddingSpace } from './schemas.js';
2
+ /** The prepared form is provider-owned and never exposed as a model-facing caller input. */
3
+ export type PreparedInput = Readonly<{
4
+ readonly kind: 'text';
5
+ readonly text: string;
6
+ readonly tokenCount: number | null;
7
+ }> | Readonly<{
8
+ readonly kind: 'tokens';
9
+ readonly tokens: readonly number[];
10
+ }>;
11
+ export type ProviderUsage = Readonly<{
12
+ readonly providerReportedInputTokens: number | null;
13
+ readonly preparedInputTokens: number | null;
14
+ readonly billedTokens: number | null;
15
+ }>;
16
+ export type ProviderBatchResult = Readonly<{
17
+ readonly vectors: readonly (readonly number[])[];
18
+ readonly usage: ProviderUsage;
19
+ }>;
20
+ export interface EmbeddingsProvider {
21
+ readonly route: EmbeddingRouteId;
22
+ readonly model: string;
23
+ readonly space: EmbeddingSpace;
24
+ /** Mandatory provider request boundaries. Infinity means no declared request-level ceiling. */
25
+ readonly maxRequestInputs: number;
26
+ readonly maxRequestTokens: number;
27
+ prepare(text: string, signal: AbortSignal): Promise<PreparedInput>;
28
+ embed(inputs: readonly PreparedInput[], signal: AbortSignal, context: EmbeddingContext | undefined): Promise<ProviderBatchResult>;
29
+ close(): Promise<void>;
30
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ import { type EmbeddingDiagnostic, type EmbeddingRoute, type EmbeddingSettings, type EmbeddingSpace } from './schemas.js';
2
+ import type { EmbeddingsProvider } from './provider-types.js';
3
+ export declare const OPENAI_EMBEDDING_SPACE: EmbeddingSpace;
4
+ export declare const SARVAM_EMBEDDING_SPACE: EmbeddingSpace;
5
+ export declare const routeKey: (route: EmbeddingRoute) => string;
6
+ /** Diagnostics are provider-free and never contain keys, origins or model paths. */
7
+ export declare function routeDiagnostics(settings: EmbeddingSettings, route: EmbeddingRoute): EmbeddingDiagnostic[];
8
+ export type AcquiredProvider = Readonly<{
9
+ readonly provider: EmbeddingsProvider;
10
+ readonly release: () => Promise<void>;
11
+ }>;
12
+ /** Resolve a configured route only when that route is actually about to be used. */
13
+ export declare function acquireProvider({ settings, route, signal, }: {
14
+ settings: EmbeddingSettings;
15
+ route: EmbeddingRoute;
16
+ signal: AbortSignal;
17
+ }): Promise<AcquiredProvider>;
18
+ export declare const spaceForRoute: (route: EmbeddingRoute) => EmbeddingSpace;
@@ -0,0 +1,265 @@
1
+ import { getEncoding } from 'js-tiktoken';
2
+ import { EmbeddingsError } from './errors.js';
3
+ import { EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_FORMAT_VERSION, EMBEDDING_NORMALIZATION_VERSION, } from './schemas.js';
4
+ import { fixedOrigin, headerValueIsSafe, requestJson } from './provider-http.js';
5
+ import { acquireLocalRuntime, LOCAL_EMBEDDING_SPACE } from './local-runtime.js';
6
+ import { parseBatchResponse } from './response.js';
7
+ export const OPENAI_EMBEDDING_SPACE = Object.freeze({
8
+ provider: 'openai',
9
+ model: 'text-embedding-3-small',
10
+ revision: null,
11
+ quantization: null,
12
+ runtime: null,
13
+ dimensions: 1536,
14
+ format: EMBEDDING_FORMAT_VERSION,
15
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
16
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
17
+ });
18
+ export const SARVAM_EMBEDDING_SPACE = Object.freeze({
19
+ provider: 'sarvam',
20
+ model: 'embeddinggemma-2',
21
+ revision: null,
22
+ quantization: null,
23
+ runtime: 'sarvam-v2',
24
+ dimensions: 768,
25
+ format: EMBEDDING_FORMAT_VERSION,
26
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
27
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
28
+ });
29
+ const OPENAI_MODEL = 'text-embedding-3-small';
30
+ const SARVAM_MODEL = 'embeddinggemma-2';
31
+ const SARVAM_ORIGIN = 'https://api.sarvam.ai';
32
+ const OPENAI_MAX_INPUT_TOKENS = 8192;
33
+ const OPENAI_MAX_REQUEST_INPUTS = 2048;
34
+ const OPENAI_MAX_REQUEST_TOKENS = 300000;
35
+ const trim = (value) => {
36
+ const trimmed = value?.trim();
37
+ return trimmed === undefined || trimmed === '' ? undefined : trimmed;
38
+ };
39
+ export const routeKey = (route) => `${route.provider}\u0000${route.model}`;
40
+ /** Diagnostics are provider-free and never contain keys, origins or model paths. */
41
+ export function routeDiagnostics(settings, route) {
42
+ const diagnostics = [];
43
+ const add = (code, severity = 'error') => {
44
+ diagnostics.push({ code, severity });
45
+ };
46
+ switch (route.provider) {
47
+ case 'local': {
48
+ const local = settings.providers?.local;
49
+ if (trim(local?.executable) === undefined || trim(local?.modelPath) === undefined)
50
+ add('local-assets-unconfigured');
51
+ break;
52
+ }
53
+ case 'openai':
54
+ if (trim(settings.providers?.openai?.apiKey) === undefined && trim(process.env.OPENAI_API_KEY) === undefined)
55
+ add('openai-key-unconfigured');
56
+ break;
57
+ case 'sarvam':
58
+ if (trim(settings.providers?.sarvam?.apiKey) === undefined && trim(process.env.SARVAM_API_KEY) === undefined)
59
+ add('sarvam-key-unconfigured');
60
+ break;
61
+ case 'gateway': {
62
+ const gateway = settings.providers?.gateway;
63
+ if (trim(gateway?.baseUrl) === undefined && trim(process.env.LITELLM_BASE_URL) === undefined)
64
+ add('gateway-base-url-unconfigured');
65
+ if (trim(gateway?.apiKey) === undefined && trim(process.env.LITELLM_INFERENCE_KEY) === undefined)
66
+ add('gateway-key-unconfigured');
67
+ break;
68
+ }
69
+ }
70
+ return diagnostics;
71
+ }
72
+ const credential = (configured, env) => {
73
+ const value = trim(configured) ?? trim(env);
74
+ if (value === undefined)
75
+ throw new EmbeddingsError('missing-credentials');
76
+ return value;
77
+ };
78
+ /** The documented text-string path avoids the token-array schema contradiction without truncating. */
79
+ const openAIPrepare = (encoding, text, signal) => {
80
+ signal.throwIfAborted();
81
+ const prepared = EMBEDDING_DOCUMENT_PREFIX + text;
82
+ const tokens = encoding.encode(prepared, [], []);
83
+ if (tokens.length > OPENAI_MAX_INPUT_TOKENS)
84
+ throw new EmbeddingsError('input-too-long');
85
+ if (encoding.decode(tokens) !== prepared)
86
+ throw new EmbeddingsError('tokenizer-roundtrip-failed');
87
+ return { kind: 'text', text: prepared, tokenCount: tokens.length };
88
+ };
89
+ const preparedTokens = (inputs) => inputs.reduce((sum, input) => sum + (input.kind === 'tokens' ? input.tokens.length : (input.tokenCount ?? 0)), 0);
90
+ const providerTexts = (inputs) => inputs.map((input) => {
91
+ if (input.kind !== 'text')
92
+ throw new EmbeddingsError('provider-response-invalid');
93
+ return input.text;
94
+ });
95
+ class OpenAiProvider {
96
+ route = 'openai';
97
+ model = OPENAI_MODEL;
98
+ space = OPENAI_EMBEDDING_SPACE;
99
+ maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
100
+ maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
101
+ #encoding = getEncoding('cl100k_base');
102
+ #key;
103
+ constructor(key) {
104
+ this.#key = key;
105
+ }
106
+ async prepare(text, signal) {
107
+ return openAIPrepare(this.#encoding, text, signal);
108
+ }
109
+ async embed(inputs, signal) {
110
+ const response = await requestJson({
111
+ url: new URL('https://api.openai.com/v1/embeddings'),
112
+ signal,
113
+ headers: { authorization: `Bearer ${this.#key}` },
114
+ body: {
115
+ model: this.model,
116
+ dimensions: this.space.dimensions,
117
+ input: providerTexts(inputs),
118
+ encoding_format: 'float',
119
+ },
120
+ });
121
+ return parseBatchResponse({
122
+ response,
123
+ space: this.space,
124
+ expectedPreparedTokens: preparedTokens(inputs),
125
+ preparedInputTokens: preparedTokens(inputs),
126
+ });
127
+ }
128
+ async close() {
129
+ // js-tiktoken is pure JavaScript and owns no process or handle.
130
+ }
131
+ }
132
+ class SarvamProvider {
133
+ route = 'sarvam';
134
+ model = SARVAM_MODEL;
135
+ space = SARVAM_EMBEDDING_SPACE;
136
+ // The service enforces its documented per-string token estimate and publishes no aggregate cap.
137
+ maxRequestInputs = Number.POSITIVE_INFINITY;
138
+ maxRequestTokens = Number.POSITIVE_INFINITY;
139
+ #key;
140
+ constructor(key) {
141
+ this.#key = key;
142
+ }
143
+ async prepare(text, signal) {
144
+ signal.throwIfAborted();
145
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
146
+ }
147
+ async embed(inputs, signal) {
148
+ const response = await requestJson({
149
+ url: new URL('/v2/embeddings', SARVAM_ORIGIN),
150
+ signal,
151
+ headers: { 'api-subscription-key': this.#key },
152
+ body: { model: this.model, input: providerTexts(inputs), encoding_format: 'float' },
153
+ });
154
+ return parseBatchResponse({ response, space: this.space, expectedModels: [this.model] });
155
+ }
156
+ async close() {
157
+ // Native fetch owns no long-lived resource.
158
+ }
159
+ }
160
+ class GatewayProvider {
161
+ route = 'gateway';
162
+ model;
163
+ space = OPENAI_EMBEDDING_SPACE;
164
+ maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
165
+ maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
166
+ #encoding = getEncoding('cl100k_base');
167
+ #origin;
168
+ #key;
169
+ #stage;
170
+ constructor(config, origin, key) {
171
+ this.model = config.model;
172
+ this.#origin = origin;
173
+ this.#key = key;
174
+ this.#stage = config.stage;
175
+ }
176
+ async prepare(text, signal) {
177
+ return openAIPrepare(this.#encoding, text, signal);
178
+ }
179
+ async embed(inputs, signal, context) {
180
+ if (context === undefined ||
181
+ !headerValueIsSafe(context.endUser) ||
182
+ context.tags.length === 0 ||
183
+ context.tags.some((tag) => !headerValueIsSafe(tag)))
184
+ throw new EmbeddingsError('attribution-unavailable');
185
+ const response = await requestJson({
186
+ url: new URL('/v1/embeddings', this.#origin),
187
+ signal,
188
+ headers: {
189
+ authorization: `Bearer ${this.#key}`,
190
+ 'x-litellm-customer-id': context.endUser,
191
+ 'x-litellm-tags': context.tags.join(','),
192
+ },
193
+ body: {
194
+ model: this.model,
195
+ dimensions: this.space.dimensions,
196
+ input: providerTexts(inputs),
197
+ encoding_format: 'float',
198
+ },
199
+ });
200
+ const count = preparedTokens(inputs);
201
+ return parseBatchResponse({
202
+ response,
203
+ space: this.space,
204
+ expectedModels: [this.space.model, this.model],
205
+ expectedPreparedTokens: count,
206
+ preparedInputTokens: count,
207
+ });
208
+ }
209
+ async close() {
210
+ // js-tiktoken is pure JavaScript and owns no process or handle.
211
+ }
212
+ }
213
+ const noRelease = async () => undefined;
214
+ /** Resolve a configured route only when that route is actually about to be used. */
215
+ export async function acquireProvider({ settings, route, signal, }) {
216
+ switch (route.provider) {
217
+ case 'local': {
218
+ const local = settings.providers?.local;
219
+ const executable = trim(local?.executable);
220
+ const modelPath = trim(local?.modelPath);
221
+ if (local === undefined || executable === undefined || modelPath === undefined)
222
+ throw new EmbeddingsError('configuration-invalid');
223
+ const acquired = await acquireLocalRuntime({ executable, modelPath, port: local.port ?? 8791 }, signal);
224
+ return { provider: acquired.provider, release: acquired.release };
225
+ }
226
+ case 'openai':
227
+ return {
228
+ provider: new OpenAiProvider(credential(settings.providers?.openai?.apiKey, process.env.OPENAI_API_KEY)),
229
+ release: noRelease,
230
+ };
231
+ case 'sarvam':
232
+ return {
233
+ provider: new SarvamProvider(credential(settings.providers?.sarvam?.apiKey, process.env.SARVAM_API_KEY)),
234
+ release: noRelease,
235
+ };
236
+ case 'gateway': {
237
+ const configured = settings.providers?.gateway;
238
+ const baseUrl = trim(configured?.baseUrl) ?? trim(process.env.LITELLM_BASE_URL);
239
+ const key = credential(configured?.apiKey, process.env.LITELLM_INFERENCE_KEY);
240
+ const rawModel = trim(configured?.model) ?? trim(process.env.LITELLM_EMBEDDING_MODEL) ?? OPENAI_MODEL;
241
+ if (rawModel !== 'text-embedding-3-small' &&
242
+ rawModel !== 'openai/text-embedding-3-small')
243
+ throw new EmbeddingsError('configuration-invalid');
244
+ const stage = configured?.stage ?? 'dev';
245
+ if (baseUrl === undefined)
246
+ throw new EmbeddingsError('configuration-invalid');
247
+ const gateway = { baseUrl, apiKey: key, model: rawModel, stage };
248
+ return {
249
+ provider: new GatewayProvider(gateway, fixedOrigin(baseUrl), key),
250
+ release: noRelease,
251
+ };
252
+ }
253
+ }
254
+ }
255
+ export const spaceForRoute = (route) => {
256
+ switch (route.provider) {
257
+ case 'local':
258
+ return LOCAL_EMBEDDING_SPACE;
259
+ case 'openai':
260
+ case 'gateway':
261
+ return OPENAI_EMBEDDING_SPACE;
262
+ case 'sarvam':
263
+ return SARVAM_EMBEDDING_SPACE;
264
+ }
265
+ };
@@ -0,0 +1,11 @@
1
+ import type { ProviderBatchResult } from './provider-types.js';
2
+ import type { EmbeddingSpace } from './schemas.js';
3
+ /** Stable, overflow-safe L2 normalization. The identity is recorded in every success outcome. */
4
+ export declare function normalizeVector(vector: readonly number[], dimensions: number): number[];
5
+ export declare function parseBatchResponse(args: {
6
+ response: unknown;
7
+ space: EmbeddingSpace;
8
+ expectedModels?: readonly string[];
9
+ expectedPreparedTokens?: number | null;
10
+ preparedInputTokens?: number | null;
11
+ }): ProviderBatchResult;
@@ -0,0 +1,62 @@
1
+ import { Type } from 'typebox';
2
+ import { Value } from 'typebox/value';
3
+ import { EmbeddingsError } from './errors.js';
4
+ const responseSchema = Type.Object({
5
+ model: Type.Optional(Type.String({ minLength: 1 })),
6
+ data: Type.Array(Type.Object({
7
+ index: Type.Integer({ minimum: 0 }),
8
+ embedding: Type.Array(Type.Number()),
9
+ })),
10
+ usage: Type.Object({
11
+ prompt_tokens: Type.Integer({ minimum: 0 }),
12
+ }),
13
+ });
14
+ /** Stable, overflow-safe L2 normalization. The identity is recorded in every success outcome. */
15
+ export function normalizeVector(vector, dimensions) {
16
+ if (vector.length !== dimensions || vector.some((value) => !Number.isFinite(value)))
17
+ throw new EmbeddingsError('vector-invalid');
18
+ const scale = vector.reduce((largest, value) => Math.max(largest, Math.abs(value)), 0);
19
+ if (scale === 0)
20
+ throw new EmbeddingsError('vector-zero');
21
+ const norm = Math.sqrt(vector.reduce((sum, value) => sum + (value / scale) ** 2, 0));
22
+ return vector.map((value) => value / scale / norm);
23
+ }
24
+ export function parseBatchResponse(args) {
25
+ const prepared = args.preparedInputTokens ?? args.expectedPreparedTokens ?? null;
26
+ if (!Value.Check(responseSchema, args.response))
27
+ throw new EmbeddingsError('provider-response-invalid', {
28
+ knownUsage: { preparedInputTokens: prepared },
29
+ });
30
+ const parsed = args.response;
31
+ const known = (code) => new EmbeddingsError(code, {
32
+ knownUsage: {
33
+ providerReportedInputTokens: parsed.usage.prompt_tokens,
34
+ preparedInputTokens: prepared,
35
+ },
36
+ });
37
+ const admitted = args.expectedModels ?? [args.space.model];
38
+ if (admitted.length > 0 && (parsed.model === undefined || !admitted.includes(parsed.model)))
39
+ throw known('provider-response-mismatch');
40
+ if (prepared !== null && parsed.usage.prompt_tokens !== prepared)
41
+ throw known('provider-response-mismatch');
42
+ const ordered = [...parsed.data].sort((left, right) => left.index - right.index);
43
+ if (ordered.some((item, index) => item.index !== index))
44
+ throw known('provider-response-mismatch');
45
+ let vectors;
46
+ try {
47
+ vectors = ordered.map((item) => normalizeVector(item.embedding, args.space.dimensions));
48
+ }
49
+ catch (error) {
50
+ if (error instanceof EmbeddingsError)
51
+ throw known(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid');
52
+ throw error;
53
+ }
54
+ return {
55
+ vectors,
56
+ usage: {
57
+ providerReportedInputTokens: parsed.usage.prompt_tokens,
58
+ preparedInputTokens: prepared,
59
+ billedTokens: null,
60
+ },
61
+ };
62
+ }
@@ -0,0 +1,19 @@
1
+ import { type EmbeddingCompareResult, type EmbeddingContext, type EmbeddingDescribe, type EmbeddingRequest, type EmbeddingResult, type EmbeddingSettings } from './schemas.js';
2
+ export interface EmbeddingsRuntime {
3
+ /** Acquire the selected local child at MCP startup; cloud selections start no local process. */
4
+ start(): Promise<void>;
5
+ embed(request: EmbeddingRequest, options?: {
6
+ signal?: AbortSignal | undefined;
7
+ context?: EmbeddingContext | undefined;
8
+ }): Promise<EmbeddingResult>;
9
+ compare(request: EmbeddingRequest, options?: {
10
+ signal?: AbortSignal | undefined;
11
+ context?: EmbeddingContext | undefined;
12
+ }): Promise<EmbeddingCompareResult>;
13
+ describe(): EmbeddingDescribe;
14
+ close(): Promise<void>;
15
+ }
16
+ export declare function createEmbeddingsRuntime(args: {
17
+ settings: EmbeddingSettings;
18
+ cwd?: string | undefined;
19
+ }): EmbeddingsRuntime;