LibreChat/packages/data-provider/src/mcp.ts
Danny Avila a058963a9f
👤 feat: User Placeholder Variables for Custom Endpoint Headers (#7993)
* 🔧 refactor: move `processMCPEnv` from `librechat-data-provider` and move to `@librechat/api`

* 🔧 refactor: Update resolveHeaders import paths

* 🔧 refactor: Enhance resolveHeaders to support user and custom variables

- Updated resolveHeaders function to accept user and custom user variables for placeholder replacement.
- Modified header resolution in multiple client and controller files to utilize the enhanced resolveHeaders functionality.
- Added comprehensive tests for resolveHeaders to ensure correct processing of user and custom variables.

* 🔧 fix: Update user ID placeholder processing in env.ts

* 🔧 fix: Remove arguments passing this.user rather than req.user

- Updated multiple client and controller files to call resolveHeaders without the user parameter

* 🔧 refactor: Enhance processUserPlaceholders to be more readable / less nested

* 🔧 refactor: Update processUserPlaceholders to pass all tests in mpc.spec.ts and env.spec.ts

* chore: remove legacy ChatGPTClient

* chore: remove LLM initialization code

* chore: initial deprecation removal of `gptPlugins`

* chore: remove cohere-ai dependency from package.json and package-lock.json

* chore: update brace-expansion to version 2.0.2 and add license information

* chore: remove PluginsClient test file

* chore: remove legacy

* ci: remove deprecated sendMessage/getCompletion/chatCompletion tests

---------

Co-authored-by: Dustin Healy <54083382+dustinhealy@users.noreply.github.com>
2025-06-23 12:39:27 -04:00

154 lines
4.7 KiB
TypeScript

import { z } from 'zod';
import { TokenExchangeMethodEnum } from './types/agents';
import { extractEnvVariable } from './utils';
const BaseOptionsSchema = z.object({
iconPath: z.string().optional(),
timeout: z.number().optional(),
initTimeout: z.number().optional(),
/** Controls visibility in chat dropdown menu (MCPSelect) */
chatMenu: z.boolean().optional(),
/**
* Controls server instruction behavior:
* - undefined/not set: No instructions included (default)
* - true: Use server-provided instructions
* - string: Use custom instructions (overrides server-provided)
*/
serverInstructions: z.union([z.boolean(), z.string()]).optional(),
/**
* OAuth configuration for SSE and Streamable HTTP transports
* - Optional: OAuth can be auto-discovered on 401 responses
* - Pre-configured values will skip discovery steps
*/
oauth: z
.object({
/** OAuth authorization endpoint (optional - can be auto-discovered) */
authorization_url: z.string().url().optional(),
/** OAuth token endpoint (optional - can be auto-discovered) */
token_url: z.string().url().optional(),
/** OAuth client ID (optional - can use dynamic registration) */
client_id: z.string().optional(),
/** OAuth client secret (optional - can use dynamic registration) */
client_secret: z.string().optional(),
/** OAuth scopes to request */
scope: z.string().optional(),
/** OAuth redirect URI (defaults to /api/mcp/{serverName}/oauth/callback) */
redirect_uri: z.string().url().optional(),
/** Token exchange method */
token_exchange_method: z.nativeEnum(TokenExchangeMethodEnum).optional(),
})
.optional(),
customUserVars: z
.record(
z.string(),
z.object({
title: z.string(),
description: z.string(),
}),
)
.optional(),
});
export const StdioOptionsSchema = BaseOptionsSchema.extend({
type: z.literal('stdio').optional(),
/**
* The executable to run to start the server.
*/
command: z.string(),
/**
* Command line arguments to pass to the executable.
*/
args: z.array(z.string()),
/**
* The environment to use when spawning the process.
*
* If not specified, the result of getDefaultEnvironment() will be used.
* Environment variables can be referenced using ${VAR_NAME} syntax.
*/
env: z
.record(z.string(), z.string())
.optional()
.transform((env) => {
if (!env) {
return env;
}
const processedEnv: Record<string, string> = {};
for (const [key, value] of Object.entries(env)) {
processedEnv[key] = extractEnvVariable(value);
}
return processedEnv;
}),
/**
* How to handle stderr of the child process. This matches the semantics of Node's `child_process.spawn`.
*
* @type {import('node:child_process').IOType | import('node:stream').Stream | number}
*
* The default is "inherit", meaning messages to stderr will be printed to the parent process's stderr.
*/
stderr: z.any().optional(),
});
export const WebSocketOptionsSchema = BaseOptionsSchema.extend({
type: z.literal('websocket').optional(),
url: z
.string()
.transform((val: string) => extractEnvVariable(val))
.pipe(z.string().url())
.refine(
(val: string) => {
const protocol = new URL(val).protocol;
return protocol === 'ws:' || protocol === 'wss:';
},
{
message: 'WebSocket URL must start with ws:// or wss://',
},
),
});
export const SSEOptionsSchema = BaseOptionsSchema.extend({
type: z.literal('sse').optional(),
headers: z.record(z.string(), z.string()).optional(),
url: z
.string()
.transform((val: string) => extractEnvVariable(val))
.pipe(z.string().url())
.refine(
(val: string) => {
const protocol = new URL(val).protocol;
return protocol !== 'ws:' && protocol !== 'wss:';
},
{
message: 'SSE URL must not start with ws:// or wss://',
},
),
});
export const StreamableHTTPOptionsSchema = BaseOptionsSchema.extend({
type: z.literal('streamable-http'),
headers: z.record(z.string(), z.string()).optional(),
url: z
.string()
.transform((val: string) => extractEnvVariable(val))
.pipe(z.string().url())
.refine(
(val: string) => {
const protocol = new URL(val).protocol;
return protocol !== 'ws:' && protocol !== 'wss:';
},
{
message: 'Streamable HTTP URL must not start with ws:// or wss://',
},
),
});
export const MCPOptionsSchema = z.union([
StdioOptionsSchema,
WebSocketOptionsSchema,
SSEOptionsSchema,
StreamableHTTPOptionsSchema,
]);
export const MCPServersSchema = z.record(z.string(), MCPOptionsSchema);
export type MCPOptions = z.infer<typeof MCPOptionsSchema>;