@scoheart/x-search-mcp 0.2.0 → 0.4.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 (105) hide show
  1. package/README.md +59 -75
  2. package/TOOL.md +28 -17
  3. package/dist/package.json +8 -1
  4. package/dist/src/auth.d.ts +14 -5
  5. package/dist/src/auth.d.ts.map +1 -1
  6. package/dist/src/auth.js +180 -118
  7. package/dist/src/auth.js.map +1 -1
  8. package/dist/src/call-log.d.ts.map +1 -1
  9. package/dist/src/call-log.js +52 -33
  10. package/dist/src/call-log.js.map +1 -1
  11. package/dist/src/cli.d.ts.map +1 -1
  12. package/dist/src/cli.js +9 -4
  13. package/dist/src/cli.js.map +1 -1
  14. package/dist/src/config.d.ts +3 -1
  15. package/dist/src/config.d.ts.map +1 -1
  16. package/dist/src/config.js +4 -4
  17. package/dist/src/config.js.map +1 -1
  18. package/dist/src/device-login.d.ts +46 -0
  19. package/dist/src/device-login.d.ts.map +1 -0
  20. package/dist/src/device-login.js +72 -0
  21. package/dist/src/device-login.js.map +1 -0
  22. package/dist/src/http-config.d.ts +9 -0
  23. package/dist/src/http-config.d.ts.map +1 -1
  24. package/dist/src/http-config.js +10 -5
  25. package/dist/src/http-config.js.map +1 -1
  26. package/dist/src/http-server.d.ts +10 -2
  27. package/dist/src/http-server.d.ts.map +1 -1
  28. package/dist/src/http-server.js +46 -15
  29. package/dist/src/http-server.js.map +1 -1
  30. package/dist/src/index.d.ts +3 -0
  31. package/dist/src/index.d.ts.map +1 -1
  32. package/dist/src/index.js +3 -0
  33. package/dist/src/index.js.map +1 -1
  34. package/dist/src/multi-user/bindings.d.ts +21 -0
  35. package/dist/src/multi-user/bindings.d.ts.map +1 -0
  36. package/dist/src/multi-user/bindings.js +129 -0
  37. package/dist/src/multi-user/bindings.js.map +1 -0
  38. package/dist/src/multi-user/cli.d.ts +23 -0
  39. package/dist/src/multi-user/cli.d.ts.map +1 -0
  40. package/dist/src/multi-user/cli.js +82 -0
  41. package/dist/src/multi-user/cli.js.map +1 -0
  42. package/dist/src/multi-user/identity.d.ts +17 -0
  43. package/dist/src/multi-user/identity.d.ts.map +1 -0
  44. package/dist/src/multi-user/identity.js +78 -0
  45. package/dist/src/multi-user/identity.js.map +1 -0
  46. package/dist/src/multi-user/keys.d.ts +17 -0
  47. package/dist/src/multi-user/keys.d.ts.map +1 -0
  48. package/dist/src/multi-user/keys.js +54 -0
  49. package/dist/src/multi-user/keys.js.map +1 -0
  50. package/dist/src/multi-user/kms.d.ts +10 -0
  51. package/dist/src/multi-user/kms.d.ts.map +1 -0
  52. package/dist/src/multi-user/kms.js +83 -0
  53. package/dist/src/multi-user/kms.js.map +1 -0
  54. package/dist/src/multi-user/service.d.ts +13 -0
  55. package/dist/src/multi-user/service.d.ts.map +1 -0
  56. package/dist/src/multi-user/service.js +92 -0
  57. package/dist/src/multi-user/service.js.map +1 -0
  58. package/dist/src/multi-user/settings.d.ts +9 -0
  59. package/dist/src/multi-user/settings.d.ts.map +1 -0
  60. package/dist/src/multi-user/settings.js +323 -0
  61. package/dist/src/multi-user/settings.js.map +1 -0
  62. package/dist/src/search-input.d.ts +43 -0
  63. package/dist/src/search-input.d.ts.map +1 -0
  64. package/dist/src/search-input.js +105 -0
  65. package/dist/src/search-input.js.map +1 -0
  66. package/dist/src/search-response.d.ts +6 -0
  67. package/dist/src/search-response.d.ts.map +1 -0
  68. package/dist/src/search-response.js +125 -0
  69. package/dist/src/search-response.js.map +1 -0
  70. package/dist/src/search.d.ts +5 -20
  71. package/dist/src/search.d.ts.map +1 -1
  72. package/dist/src/search.js +67 -332
  73. package/dist/src/search.js.map +1 -1
  74. package/dist/src/server.d.ts +9 -1
  75. package/dist/src/server.d.ts.map +1 -1
  76. package/dist/src/server.js +88 -81
  77. package/dist/src/server.js.map +1 -1
  78. package/dist/src/tool-contract.d.ts +150 -0
  79. package/dist/src/tool-contract.d.ts.map +1 -0
  80. package/dist/src/tool-contract.js +83 -0
  81. package/dist/src/tool-contract.js.map +1 -0
  82. package/docs/multi-user.md +108 -0
  83. package/examples/codex.toml +1 -1
  84. package/examples/mcp.json +1 -1
  85. package/package.json +8 -1
  86. package/src/auth.ts +178 -125
  87. package/src/call-log.ts +52 -31
  88. package/src/cli.ts +9 -4
  89. package/src/config.ts +4 -4
  90. package/src/device-login.ts +84 -0
  91. package/src/http-config.ts +11 -5
  92. package/src/http-server.ts +55 -18
  93. package/src/index.ts +3 -0
  94. package/src/multi-user/bindings.ts +135 -0
  95. package/src/multi-user/cli.ts +78 -0
  96. package/src/multi-user/identity.ts +83 -0
  97. package/src/multi-user/keys.ts +66 -0
  98. package/src/multi-user/kms.ts +87 -0
  99. package/src/multi-user/service.ts +92 -0
  100. package/src/multi-user/settings.ts +329 -0
  101. package/src/search-input.ts +113 -0
  102. package/src/search-response.ts +127 -0
  103. package/src/search.ts +130 -426
  104. package/src/server.ts +97 -82
  105. package/src/tool-contract.ts +90 -0
@@ -0,0 +1,78 @@
1
+ import { parseHttpOptions } from '../http-config.js';
2
+ import type { RunningHttpServer } from '../http-server.js';
3
+ import { BindingStore } from './bindings.js';
4
+ import { httpsUrl } from './identity.js';
5
+ import { loadLocalKeyProvider, readPrivateFile } from './keys.js';
6
+ import { startMultiUserHttp, type MultiUserOptions } from './service.js';
7
+
8
+ const prefix = 'X_SEARCH_MULTI_USER_';
9
+
10
+ function readClientSecret(file: string): string {
11
+ try {
12
+ const buffer = readPrivateFile(file, 4096);
13
+ try {
14
+ const secret = buffer.toString('utf8').trim();
15
+ if (!secret || /\s/.test(secret) || buffer.length > 4096) throw new Error('Invalid secret');
16
+ return secret;
17
+ } finally { buffer.fill(0); }
18
+ } catch {
19
+ throw new Error(`${prefix}OIDC_CLIENT_SECRET_FILE must be a non-empty private file owned by the service user`);
20
+ }
21
+ }
22
+
23
+ export function loadMultiUserOptions(args: string[], env: NodeJS.ProcessEnv = process.env) {
24
+ const dev = args.includes('--dev-local-key');
25
+ const { host, port, path, allowedHosts, allowedOrigins, tokenFile } = parseHttpOptions(
26
+ args.filter(argument => argument !== '--dev-local-key'), env,
27
+ );
28
+ if (tokenFile) throw new Error('--token-file applies only to single-account HTTP');
29
+ if (allowedHosts.length) throw new Error('Managed HTTP derives the allowed public host from X_SEARCH_MULTI_USER_PUBLIC_URL');
30
+ if (host !== '127.0.0.1' && host !== '::1') throw new Error('Managed HTTP must bind to loopback');
31
+ const required = (name: string): string => {
32
+ const value = env[prefix + name]?.trim();
33
+ if (!value) throw new Error(`Set ${prefix}${name}`);
34
+ return value;
35
+ };
36
+ const publicUrl = httpsUrl(required('PUBLIC_URL'), 'X_SEARCH_MULTI_USER_PUBLIC_URL');
37
+ if (path !== undefined && path !== publicUrl.pathname) {
38
+ throw new Error('Managed HTTP path must match X_SEARCH_MULTI_USER_PUBLIC_URL');
39
+ }
40
+ const options: MultiUserOptions = {
41
+ publicUrl: publicUrl.href,
42
+ host, port, allowedOrigins,
43
+ issuer: required('ISSUER'),
44
+ jwksUri: required('JWKS_URL'),
45
+ scope: env[prefix + 'SCOPE']?.trim() || 'openid',
46
+ allowedSubjects: required('ALLOWED_SUBJECTS').split(',').map(subject => subject.trim()),
47
+ settings: {
48
+ clientId: required('OIDC_CLIENT_ID'),
49
+ clientSecret: readClientSecret(required('OIDC_CLIENT_SECRET_FILE')),
50
+ },
51
+ };
52
+ const database = required('DATABASE');
53
+ const keys = dev
54
+ ? { type: 'local', file: required('DEV_KEY_FILE') } as const
55
+ : { type: 'kms', options: {
56
+ region: required('KMS_REGION'),
57
+ keyId: required('KMS_KEY_ID'),
58
+ roleName: required('KMS_ROLE_NAME'),
59
+ endpoint: env[prefix + 'KMS_ENDPOINT']?.trim() || undefined,
60
+ caFile: env[prefix + 'KMS_CA_FILE']?.trim() || undefined,
61
+ } } as const;
62
+ return { options, database, keys };
63
+ }
64
+
65
+ export async function startMultiUserCli(args: string[]): Promise<RunningHttpServer> {
66
+ const { options, database, keys } = loadMultiUserOptions(args);
67
+ const provider = keys.type === 'local' ? loadLocalKeyProvider(keys.file)
68
+ : (await import('./kms.js')).createAliyunKeyProvider(keys.options);
69
+ const store = new BindingStore(database, provider);
70
+ try {
71
+ const service = await startMultiUserHttp(options, store);
72
+ let closing: Promise<void> | undefined;
73
+ return { url: service.url, close: () => closing ??= service.close().finally(() => store.close()) };
74
+ } catch (error) {
75
+ store.close();
76
+ throw error;
77
+ }
78
+ }
@@ -0,0 +1,83 @@
1
+ import { createRemoteJWKSet, customFetch, errors, jwtVerify } from 'jose';
2
+ import type { AuthInfo } from '@modelcontextprotocol/server';
3
+ import { Agent, fetch as undiciFetch } from 'undici';
4
+ import type { HttpAuthentication } from '../http-server.js';
5
+ import type { Principal } from './bindings.js';
6
+
7
+ export interface IdentityOptions {
8
+ issuer: string;
9
+ jwksUri: string;
10
+ scope: string;
11
+ allowedSubjects: readonly string[];
12
+ identityFetch?: typeof fetch;
13
+ }
14
+
15
+ const directIdentityAgent = new Agent();
16
+ // Use Undici's matched fetch/dispatcher pair. OAuth libraries accept its Fetch API response at runtime.
17
+ const directFetch = undiciFetch as unknown as typeof fetch;
18
+
19
+ export const fetchIdentity: typeof fetch = (input, init) => {
20
+ const options = { ...init, dispatcher: directIdentityAgent };
21
+ return directFetch(input, options);
22
+ };
23
+
24
+ export function httpsUrl(value: string, name: string): URL {
25
+ let url: URL;
26
+ try { url = new URL(value); } catch { throw new Error(`${name} must be an absolute HTTPS URL`); }
27
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) {
28
+ throw new Error(`${name} must be an HTTPS URL without credentials, query, or fragment`);
29
+ }
30
+ return url;
31
+ }
32
+
33
+ export function createIdentity(options: IdentityOptions, resource: URL, settingsClientId: string) {
34
+ const { issuer, scope } = options;
35
+ httpsUrl(issuer, 'OAuth issuer');
36
+ if (!/^[A-Za-z0-9:_./-]{1,128}$/.test(scope)) throw new Error('Set a valid MCP OAuth scope');
37
+ const subjects = new Set(options.allowedSubjects);
38
+ if (!subjects.size || [...subjects].some(subject => !/^[\x21-\x7e]{1,255}$/.test(subject))) {
39
+ throw new Error('Supply an explicit list of invited OAuth subject IDs');
40
+ }
41
+ const keyset = createRemoteJWKSet(httpsUrl(options.jwksUri, 'OAuth JWKS URL'), {
42
+ timeoutDuration: 5_000,
43
+ [customFetch]: options.identityFetch ?? fetchIdentity,
44
+ });
45
+ const invited = (subject: unknown): subject is string => typeof subject === 'string' && subjects.has(subject);
46
+
47
+ const verify: HttpAuthentication['verify'] = async token => {
48
+ let payload;
49
+ try {
50
+ ({ payload } = await jwtVerify(token, keyset, {
51
+ issuer,
52
+ audience: resource.pathname === '/' ? resource.origin : resource.href,
53
+ algorithms: ['RS256', 'ES256'],
54
+ requiredClaims: ['sub', 'exp'],
55
+ }));
56
+ } catch (error) {
57
+ if (error instanceof errors.JWKSTimeout) throw new Error('OAuth signing keys are unavailable');
58
+ if (error instanceof errors.JOSEError) return null;
59
+ throw error;
60
+ }
61
+ // Accept resource access tokens for this MCP alone. Settings ID tokens have
62
+ // their own client audience and cannot authorize MCP tool calls.
63
+ const clientId = payload.client_id;
64
+ if ((Array.isArray(payload.aud) && payload.aud.length !== 1)
65
+ || typeof clientId !== 'string' || !clientId || clientId === settingsClientId
66
+ || payload.nonce !== undefined || payload.cnf !== undefined) {
67
+ return null;
68
+ }
69
+ if (payload.sub_profile === 'ai_agent' || !invited(payload.sub)) return 'forbidden';
70
+ const scopes = typeof payload.scope === 'string' ? payload.scope.split(/\s+/).filter(Boolean) : [];
71
+ if (!scopes.includes(scope)) return 'insufficient_scope';
72
+ return { token, clientId, scopes, expiresAt: payload.exp, resource,
73
+ extra: { issuer, subject: payload.sub } };
74
+ };
75
+
76
+ return { verify, invited };
77
+ }
78
+
79
+ export function principalFrom(auth: AuthInfo | undefined): Principal | undefined {
80
+ const { issuer, subject } = auth?.extra ?? {};
81
+ if (typeof issuer === 'string' && typeof subject === 'string') return { issuer, subject };
82
+ return undefined;
83
+ }
@@ -0,0 +1,66 @@
1
+ import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
2
+ import { closeSync, constants, fstatSync, openSync, readFileSync } from 'node:fs';
3
+
4
+ export interface DataKeyProvider {
5
+ generate(context: string): Promise<{ plaintext: Buffer; wrapped: string }>;
6
+ unwrap(wrapped: string, context: string): Promise<Buffer>;
7
+ }
8
+
9
+ export interface SealedValue {
10
+ nonce: string;
11
+ ciphertext: string;
12
+ tag: string;
13
+ }
14
+
15
+ export function seal(key: Buffer, plaintext: Buffer, context: string): SealedValue {
16
+ const nonce = randomBytes(12);
17
+ const cipher = createCipheriv('aes-256-gcm', key, nonce);
18
+ cipher.setAAD(Buffer.from(context));
19
+ return {
20
+ nonce: nonce.toString('base64'),
21
+ ciphertext: Buffer.concat([cipher.update(plaintext), cipher.final()]).toString('base64'),
22
+ tag: cipher.getAuthTag().toString('base64'),
23
+ };
24
+ }
25
+
26
+ export function open(key: Buffer, value: SealedValue, context: string): Buffer {
27
+ const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(value.nonce, 'base64'), { authTagLength: 16 });
28
+ decipher.setAAD(Buffer.from(context));
29
+ decipher.setAuthTag(Buffer.from(value.tag, 'base64'));
30
+ const plaintext = decipher.update(Buffer.from(value.ciphertext, 'base64'));
31
+ try {
32
+ return Buffer.concat([plaintext, decipher.final()]);
33
+ } finally {
34
+ plaintext.fill(0);
35
+ }
36
+ }
37
+
38
+ export function readPrivateFile(file: string, maxBytes: number): Buffer {
39
+ const descriptor = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
40
+ try {
41
+ const info = fstatSync(descriptor);
42
+ if (!info.isFile() || info.size > maxBytes || info.mode & 0o077 || info.uid !== process.getuid?.()) {
43
+ throw new Error('The secret must be a private, user-owned file');
44
+ }
45
+ return readFileSync(descriptor);
46
+ } finally {
47
+ closeSync(descriptor);
48
+ }
49
+ }
50
+
51
+ export function loadLocalKeyProvider(file: string): DataKeyProvider {
52
+ const master = readPrivateFile(file, 32);
53
+ if (master.length !== 32) {
54
+ master.fill(0);
55
+ throw new Error('The local wrapping key must contain 32 bytes');
56
+ }
57
+ return {
58
+ async generate(context) {
59
+ const plaintext = randomBytes(32);
60
+ return { plaintext, wrapped: JSON.stringify(seal(master, plaintext, context)) };
61
+ },
62
+ async unwrap(wrapped, context) {
63
+ return open(master, JSON.parse(wrapped) as SealedValue, context);
64
+ },
65
+ };
66
+ }
@@ -0,0 +1,87 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { createSecureContext } from 'node:tls';
5
+ import type { DataKeyProvider } from './keys.js';
6
+
7
+ const require = createRequire(import.meta.url);
8
+ // Alibaba Cloud's generated SDKs expose their client constructors through CommonJS.
9
+ const { default: KmsClient, GenerateDataKeyRequest, DecryptRequest } =
10
+ require('@alicloud/kms20160120') as typeof import('@alicloud/kms20160120');
11
+ const { default: Credential, Config: CredentialConfig } =
12
+ require('@alicloud/credentials') as typeof import('@alicloud/credentials');
13
+ const { $OpenApiUtil } = require('@alicloud/openapi-core') as typeof import('@alicloud/openapi-core');
14
+
15
+ export interface AliyunKmsOptions {
16
+ region: string;
17
+ keyId: string;
18
+ roleName: string;
19
+ endpoint?: string;
20
+ caFile?: string;
21
+ }
22
+
23
+ function encryptionContext(context: string) {
24
+ return { binding: createHash('sha256').update(context).digest('hex') };
25
+ }
26
+
27
+ function dataKey(body: { keyId?: string; plaintext?: string } | undefined, expectedKeyId: string): Buffer {
28
+ if (body?.keyId !== expectedKeyId || !body.plaintext || !/^[A-Za-z0-9+/]{43}=$/.test(body.plaintext)) {
29
+ throw new Error('Unexpected KMS data key response');
30
+ }
31
+ return Buffer.from(body.plaintext, 'base64');
32
+ }
33
+
34
+ export function createAliyunKeyProvider({ region, keyId, roleName, endpoint, caFile }: AliyunKmsOptions): DataKeyProvider {
35
+ if (!/^[a-z][a-z0-9-]{1,30}$/.test(region)) throw new Error('Set a valid Alibaba Cloud KMS region');
36
+ if (!/^(?:key-[a-z0-9-]{1,110}|[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})$/i.test(keyId)) {
37
+ throw new Error('Set the concrete KMS key ID');
38
+ }
39
+ if (!/^[a-zA-Z0-9-]{1,64}$/.test(roleName)) throw new Error('Set the ECS RAM role name for KMS');
40
+ const vpc = `kms-vpc.${region}.aliyuncs.com`;
41
+ const host = endpoint ?? vpc;
42
+ const dedicated = /^[a-z0-9-]{1,63}\.cryptoservice\.kms\.aliyuncs\.com$/.test(host);
43
+ if (host !== vpc && host !== `kms.${region}.aliyuncs.com` && !dedicated) {
44
+ throw new Error('Set a valid regional or dedicated Alibaba Cloud KMS endpoint');
45
+ }
46
+ if (dedicated && !caFile) throw new Error('Set the Alibaba Cloud KMS instance CA file for a dedicated endpoint');
47
+ let ca: string | undefined;
48
+ if (caFile) {
49
+ try {
50
+ ca = readFileSync(caFile, 'utf8');
51
+ if (!ca.includes('-----BEGIN CERTIFICATE-----')) throw new Error('Invalid certificate');
52
+ createSecureContext({ ca });
53
+ } catch { throw new Error('Could not load the Alibaba Cloud KMS instance CA certificate'); }
54
+ }
55
+ const credential = new Credential(new CredentialConfig({
56
+ type: 'ecs_ram_role', roleName, disableIMDSv1: true, asyncCredentialUpdateEnabled: false,
57
+ timeout: 3_000, connectTimeout: 2_000,
58
+ }));
59
+ const kms = new KmsClient(new $OpenApiUtil.Config({
60
+ credential, regionId: region, endpoint: host, protocol: 'HTTPS', ca,
61
+ noProxy: host, readTimeout: 5_000, connectTimeout: 3_000,
62
+ }));
63
+ return {
64
+ async generate(context) {
65
+ try {
66
+ const { body } = await kms.generateDataKey(new GenerateDataKeyRequest({
67
+ keyId, numberOfBytes: 32, encryptionContext: encryptionContext(context),
68
+ }));
69
+ const wrapped = body?.ciphertextBlob;
70
+ if (!wrapped || wrapped.length > 16_384) throw new Error('Unexpected KMS ciphertext');
71
+ return { plaintext: dataKey(body, keyId), wrapped };
72
+ } catch {
73
+ throw new Error('KMS could not generate a data key');
74
+ }
75
+ },
76
+ async unwrap(wrapped, context) {
77
+ try {
78
+ const { body } = await kms.decrypt(new DecryptRequest({
79
+ ciphertextBlob: wrapped, encryptionContext: encryptionContext(context),
80
+ }));
81
+ return dataKey(body, keyId);
82
+ } catch {
83
+ throw new Error('KMS could not decrypt the data key');
84
+ }
85
+ },
86
+ };
87
+ }
@@ -0,0 +1,92 @@
1
+ import { startHttp, normalizeHttpPath, type RunningHttpServer } from '../http-server.js';
2
+ import { HttpError } from '../http.js';
3
+ import { createManagedSearchServer } from '../server.js';
4
+ import { executeSearch } from '../search.js';
5
+ import type { BindingStore } from './bindings.js';
6
+ import { createIdentity, httpsUrl, principalFrom, type IdentityOptions } from './identity.js';
7
+ import { createSettings, type SettingsOptions } from './settings.js';
8
+
9
+ export interface MultiUserOptions extends IdentityOptions {
10
+ publicUrl: string;
11
+ host?: '127.0.0.1' | '::1';
12
+ port?: number;
13
+ allowedOrigins?: string[];
14
+ settings: SettingsOptions;
15
+ }
16
+
17
+ const metadataRoot = '/.well-known/oauth-protected-resource';
18
+ const searchLimit = 30;
19
+ const simultaneousLimit = 2;
20
+
21
+ export async function startMultiUserHttp(options: MultiUserOptions, store: BindingStore): Promise<RunningHttpServer> {
22
+ const resource = httpsUrl(options.publicUrl, 'MCP public URL');
23
+ const endpoint = normalizeHttpPath(resource.pathname);
24
+ if (endpoint.startsWith('/.well-known/') || endpoint === '/settings' || endpoint.startsWith('/settings/')) {
25
+ throw new Error('The MCP endpoint conflicts with an authorization or settings route');
26
+ }
27
+ const host = options.host ?? '127.0.0.1';
28
+ if (host !== '127.0.0.1' && host !== '::1') throw new Error('Managed HTTP must listen on loopback behind HTTPS');
29
+ const metadataPath = endpoint === '/' ? metadataRoot : metadataRoot + endpoint;
30
+ const metadataUrl = new URL(metadataPath, resource).href;
31
+ const settingsUrl = new URL('/settings', resource).href;
32
+ const resourceId = endpoint === '/' ? resource.origin : resource.href;
33
+ if (options.settings.clientId === resourceId) throw new Error('The settings client ID must differ from the MCP resource URL');
34
+ const identity = createIdentity(options, resource, options.settings.clientId);
35
+ const settingsRoute = await createSettings({ ...options, ...options.settings }, resource.origin, identity.invited, store);
36
+ const rates = new Map<string, { starts: number[]; active: number }>();
37
+ const metadata = JSON.stringify({
38
+ resource: resourceId,
39
+ authorization_servers: [options.issuer],
40
+ scopes_supported: [options.scope],
41
+ bearer_methods_supported: ['header'],
42
+ });
43
+
44
+ return startHttp(context => {
45
+ const user = principalFrom(context.authInfo);
46
+ return createManagedSearchServer(async (params, request) => {
47
+ if (!user) throw new HttpError('MCP_AUTH_REQUIRED', 'Sign in to this MCP server.', 401);
48
+ const now = Date.now();
49
+ const rate = rates.get(user.subject) ?? { starts: [], active: 0 };
50
+ rate.starts = rate.starts.filter(start => start > now - 60_000);
51
+ if (rate.starts.length >= searchLimit || rate.active >= simultaneousLimit) {
52
+ throw new HttpError('MCP_SEARCH_LIMIT', 'Too many searches. Wait and try again.', 429);
53
+ }
54
+ rates.set(user.subject, rate);
55
+ rate.starts.push(now);
56
+ rate.active++;
57
+ try {
58
+ return await executeSearch(params, {
59
+ signal: request.mcpReq.signal,
60
+ resolveApiKey: async () => {
61
+ let key: string | null;
62
+ try { key = await store.get(user); }
63
+ catch { throw new HttpError('XAI_KEY_UNAVAILABLE', 'Could not access your saved xAI API key.', 503); }
64
+ if (!key) throw new HttpError('XAI_KEY_REQUIRED', 'Bind your xAI API key in Settings.', 409);
65
+ return key;
66
+ },
67
+ });
68
+ } finally { rate.active--; }
69
+ }, settingsUrl);
70
+ }, {
71
+ host, port: options.port, path: endpoint, allowedHosts: [resource.hostname],
72
+ allowedOrigins: [resource.origin, ...(options.allowedOrigins ?? [])],
73
+ authentication: {
74
+ resourceMetadataUrl: metadataUrl,
75
+ scope: options.scope,
76
+ verify: identity.verify,
77
+ async route(path, request, response) {
78
+ if (path !== metadataRoot && path !== metadataPath) {
79
+ return settingsRoute(path, request, response);
80
+ }
81
+ if (request.method !== 'GET') {
82
+ response.writeHead(405, { Allow: 'GET', 'Cache-Control': 'no-store' });
83
+ response.end();
84
+ return true;
85
+ }
86
+ response.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
87
+ response.end(metadata);
88
+ return true;
89
+ },
90
+ },
91
+ });
92
+ }