Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ai): Basic support for external MCP servers (#3217)

Eric Hayes162f95b70403
diff --git a/infra/packages/shared/src/ai_tools.ts b/infra/packages/shared/src/ai_tools.ts
index 61c27d77cc..240ad9e0e5 100644
--- a/infra/packages/shared/src/ai_tools.ts
+++ b/infra/packages/shared/src/ai_tools.ts
@@ -78,6 +78,11 @@ export function getAiToolsInfra(): AiToolsInfra {
.getSecretVersionOutput({ secretId: SYNC_SERVICE_AUTH_KEY_SECRET_NAME })
.apply((s) => s.arn);
+ const MCP_CREDENTIALS_KEY_SECRET_NAME = `mcp-credentials-key-${stack}`;
+ const mcpCredentialsKeyArn: pulumi.Output<string> = aws.secretsmanager
+ .getSecretOutput({ name: MCP_CREDENTIALS_KEY_SECRET_NAME })
+ .apply((s) => s.arn);
+
const INTERNAL_AUTH_KEY_SECRET_NAME = `document-storage-service-auth-key-${stack}`;
const internalAuthKey: pulumi.Output<string> = aws.secretsmanager
.getSecretVersionOutput({ secretId: INTERNAL_AUTH_KEY_SECRET_NAME })
@@ -109,6 +114,10 @@ export function getAiToolsInfra(): AiToolsInfra {
value: getServiceUrl(ServiceUrl.STATIC_FILE_SERVICE_URL),
},
{ name: 'SYNC_SERVICE_AUTH_KEY', value: SYNC_SERVICE_AUTH_KEY_SECRET_NAME },
+ {
+ name: 'MCP_CREDENTIALS_KEY_SECRET_NAME',
+ value: MCP_CREDENTIALS_KEY_SECRET_NAME,
+ },
{
name: 'DOCUMENT_STORAGE_BUCKET',
value: pulumi.interpolate`${documentStorageBucketId}`,
@@ -137,7 +146,11 @@ export function getAiToolsInfra(): AiToolsInfra {
return {
envVars,
- secretArns: [syncServiceAuthKeyArn, cloudfrontPrivateKeySecretArn],
+ secretArns: [
+ syncServiceAuthKeyArn,
+ cloudfrontPrivateKeySecretArn,
+ mcpCredentialsKeyArn,
+ ],
queueArns: [emailScheduledQueueArn],
bucketArns: [documentStorageBucketArn, docxUploadBucketArn],
};
diff --git a/js/app/packages/service-clients/service-cognition/generated/client.ts b/js/app/packages/service-clients/service-cognition/generated/client.ts
index 37e6daa7af..c1891ad7df 100644
--- a/js/app/packages/service-clients/service-cognition/generated/client.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts
@@ -5,13 +5,16 @@
* OpenAPI spec version: 1.0.0
*/
import type {
+ AddServerRequest,
CallToolRequest,
CallToolResponse,
ChatHistory,
ChatHistoryBatchMessagesRequest,
ChatMessageError,
CreateChatRequest,
+ DeleteMcpServerParams,
DocumentTextPart,
+ ErrorResponse,
GetBatchPreviewRequest,
GetBatchPreviewResponse,
GetChatPermissionsResponse,
@@ -19,15 +22,20 @@ import type {
GetChatsForAttachmentResponse,
GetModelsResponse,
HttpSendChatMessageRequest,
+ McpAuthCallbackParams,
MemoryErrorBody,
MemoryResponse,
PatchChatRequest,
RejectToolCallRequest,
SendChatMessageResponse,
+ ServerResponse,
+ StartAuthRequest,
+ StartAuthResponse,
StopChatStreamError,
StopChatStreamRequest,
StopChatStreamResponse,
StringIDResponse,
+ UpdateServerRequest,
UpdateToolCallRequest,
UpdateToolResponseRequest,
} from './schemas';
@@ -994,6 +1002,363 @@ export const healthHandler = async (
} as healthHandlerResponse;
};
+/**
+ * @summary List all MCP servers configured for the authenticated user.
+ */
+export type listMcpServersResponse200 = {
+ data: ServerResponse[];
+ status: 200;
+};
+
+export type listMcpServersResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type listMcpServersResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type listMcpServersResponseSuccess = listMcpServersResponse200 & {
+ headers: Headers;
+};
+export type listMcpServersResponseError = (
+ | listMcpServersResponse401
+ | listMcpServersResponse500
+) & {
+ headers: Headers;
+};
+
+export type listMcpServersResponse =
+ | listMcpServersResponseSuccess
+ | listMcpServersResponseError;
+
+export const getListMcpServersUrl = () => {
+ return `/mcp/servers`;
+};
+
+export const listMcpServers = async (
+ options?: RequestInit
+): Promise<listMcpServersResponse> => {
+ const res = await fetch(getListMcpServersUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: listMcpServersResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as listMcpServersResponse;
+};
+
+/**
+ * @summary Update an existing MCP server's name or enabled status.
+ */
+export type updateMcpServerResponse200 = {
+ data: ServerResponse;
+ status: 200;
+};
+
+export type updateMcpServerResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type updateMcpServerResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type updateMcpServerResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type updateMcpServerResponseSuccess = updateMcpServerResponse200 & {
+ headers: Headers;
+};
+export type updateMcpServerResponseError = (
+ | updateMcpServerResponse401
+ | updateMcpServerResponse404
+ | updateMcpServerResponse500
+) & {
+ headers: Headers;
+};
+
+export type updateMcpServerResponse =
+ | updateMcpServerResponseSuccess
+ | updateMcpServerResponseError;
+
+export const getUpdateMcpServerUrl = () => {
+ return `/mcp/servers`;
+};
+
+export const updateMcpServer = async (
+ updateServerRequest: UpdateServerRequest,
+ options?: RequestInit
+): Promise<updateMcpServerResponse> => {
+ const res = await fetch(getUpdateMcpServerUrl(), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(updateServerRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: updateMcpServerResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as updateMcpServerResponse;
+};
+
+/**
+ * @summary Add a new MCP server for the authenticated user.
+ */
+export type addMcpServerResponse201 = {
+ data: ServerResponse;
+ status: 201;
+};
+
+export type addMcpServerResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type addMcpServerResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type addMcpServerResponseSuccess = addMcpServerResponse201 & {
+ headers: Headers;
+};
+export type addMcpServerResponseError = (
+ | addMcpServerResponse401
+ | addMcpServerResponse500
+) & {
+ headers: Headers;
+};
+
+export type addMcpServerResponse =
+ | addMcpServerResponseSuccess
+ | addMcpServerResponseError;
+
+export const getAddMcpServerUrl = () => {
+ return `/mcp/servers`;
+};
+
+export const addMcpServer = async (
+ addServerRequest: AddServerRequest,
+ options?: RequestInit
+): Promise<addMcpServerResponse> => {
+ const res = await fetch(getAddMcpServerUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(addServerRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: addMcpServerResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as addMcpServerResponse;
+};
+
+/**
+ * @summary Delete an MCP server by URL.
+ */
+export type deleteMcpServerResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type deleteMcpServerResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type deleteMcpServerResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type deleteMcpServerResponseSuccess = deleteMcpServerResponse204 & {
+ headers: Headers;
+};
+export type deleteMcpServerResponseError = (
+ | deleteMcpServerResponse401
+ | deleteMcpServerResponse500
+) & {
+ headers: Headers;
+};
+
+export type deleteMcpServerResponse =
+ | deleteMcpServerResponseSuccess
+ | deleteMcpServerResponseError;
+
+export const getDeleteMcpServerUrl = (params: DeleteMcpServerParams) => {
+ const normalizedParams = new URLSearchParams();
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString());
+ }
+ });
+
+ const stringifiedParams = normalizedParams.toString();
+
+ return stringifiedParams.length > 0
+ ? `/mcp/servers?${stringifiedParams}`
+ : `/mcp/servers`;
+};
+
+export const deleteMcpServer = async (
+ params: DeleteMcpServerParams,
+ options?: RequestInit
+): Promise<deleteMcpServerResponse> => {
+ const res = await fetch(getDeleteMcpServerUrl(params), {
+ ...options,
+ method: 'DELETE',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: deleteMcpServerResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as deleteMcpServerResponse;
+};
+
+/**
+ * @summary OAuth callback endpoint — receives code and state from the authorization server.
+ */
+export type mcpAuthCallbackResponse200 = {
+ data: void;
+ status: 200;
+};
+
+export type mcpAuthCallbackResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type mcpAuthCallbackResponseSuccess = mcpAuthCallbackResponse200 & {
+ headers: Headers;
+};
+export type mcpAuthCallbackResponseError = mcpAuthCallbackResponse500 & {
+ headers: Headers;
+};
+
+export type mcpAuthCallbackResponse =
+ | mcpAuthCallbackResponseSuccess
+ | mcpAuthCallbackResponseError;
+
+export const getMcpAuthCallbackUrl = (params: McpAuthCallbackParams) => {
+ const normalizedParams = new URLSearchParams();
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString());
+ }
+ });
+
+ const stringifiedParams = normalizedParams.toString();
+
+ return stringifiedParams.length > 0
+ ? `/mcp/servers/auth/callback?${stringifiedParams}`
+ : `/mcp/servers/auth/callback`;
+};
+
+export const mcpAuthCallback = async (
+ params: McpAuthCallbackParams,
+ options?: RequestInit
+): Promise<mcpAuthCallbackResponse> => {
+ const res = await fetch(getMcpAuthCallbackUrl(params), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: mcpAuthCallbackResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as mcpAuthCallbackResponse;
+};
+
+/**
+ * @summary Start the OAuth authorization flow for an MCP server.
+ */
+export type startMcpAuthResponse200 = {
+ data: StartAuthResponse;
+ status: 200;
+};
+
+export type startMcpAuthResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type startMcpAuthResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type startMcpAuthResponseSuccess = startMcpAuthResponse200 & {
+ headers: Headers;
+};
+export type startMcpAuthResponseError = (
+ | startMcpAuthResponse401
+ | startMcpAuthResponse500
+) & {
+ headers: Headers;
+};
+
+export type startMcpAuthResponse =
+ | startMcpAuthResponseSuccess
+ | startMcpAuthResponseError;
+
+export const getStartMcpAuthUrl = () => {
+ return `/mcp/servers/auth/start`;
+};
+
+export const startMcpAuth = async (
+ startAuthRequest: StartAuthRequest,
+ options?: RequestInit
+): Promise<startMcpAuthResponse> => {
+ const res = await fetch(getStartMcpAuthUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(startAuthRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: startMcpAuthResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as startMcpAuthResponse;
+};
+
/**
* Returns the current memory if one exists. If the memory is stale or missing,
a background generation is triggered and the endpoint returns the stale
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/addServerRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/addServerRequest.ts
new file mode 100644
index 0000000000..08a439a529
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/addServerRequest.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Request body for adding a new MCP server.
+ */
+export interface AddServerRequest {
+ /** Human-readable name for the server. */
+ server_name: string;
+ /** The MCP server's streamable HTTP URL. */
+ url: string;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/deleteMcpServerParams.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/deleteMcpServerParams.ts
new file mode 100644
index 0000000000..8d92a7e4b6
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/deleteMcpServerParams.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+export type DeleteMcpServerParams = {
+ /**
+ * The server URL to delete.
+ */
+ url: string;
+};
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/errorResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/errorResponse.ts
new file mode 100644
index 0000000000..af1451fd54
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/errorResponse.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * A plain old json error response for use with axum.
+yup, thats it.
+ */
+export interface ErrorResponse {
+ /** Message to explain failure */
+ message: string;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts
index 14fe1de243..44c0cf794d 100644
--- a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts
@@ -6,6 +6,7 @@
*/
export * from './accessLevel';
+export * from './addServerRequest';
export * from './aIModel';
export * from './assistantMessagePart';
export * from './assistantMessagePartOneOf';
@@ -102,6 +103,7 @@ export * from './conversationRecord';
export * from './createChatRequest';
export * from './createChatRequestName';
export * from './createChatRequestProjectId';
+export * from './deleteMcpServerParams';
export * from './documentCognitionServiceApiVersion';
export * from './documentReference';
export * from './documentReferenceOneOf';
@@ -110,6 +112,7 @@ export * from './documentReferenceOneOfAllOfKind';
export * from './documentTextPart';
export * from './entity';
export * from './entityType';
+export * from './errorResponse';
export * from './extractionStatusEnum';
export * from './extractionStatusEnumOneOf';
export * from './extractionStatusEnumOneOfFive';
@@ -133,6 +136,7 @@ export * from './httpSendChatMessageRequestAdditionalInstructions';
export * from './httpSendChatMessageRequestAttachments';
export * from './httpSendChatMessageRequestChatId';
export * from './jwtPayload';
+export * from './mcpAuthCallbackParams';
export * from './memoryErrorBody';
export * from './memoryResponse';
export * from './messageWithAttachments';
@@ -155,9 +159,12 @@ export * from './sendChatMessagePayloadAllOf';
export * from './sendChatMessagePayloadAllOfAdditionalInstructions';
export * from './sendChatMessagePayloadAllOfAttachments';
export * from './sendChatMessageResponse';
+export * from './serverResponse';
export * from './sharePermissionV2';
export * from './sharePermissionV2ChannelSharePermissions';
export * from './sharePermissionV2PublicAccessLevel';
+export * from './startAuthRequest';
+export * from './startAuthResponse';
export * from './stopChatStreamError';
export * from './stopChatStreamRequest';
export * from './stopChatStreamResponse';
@@ -179,6 +186,9 @@ export * from './toolSetOneOfType';
export * from './updateChannelSharePermission';
export * from './updateChannelSharePermissionAccessLevel';
export * from './updateOperation';
+export * from './updateServerRequest';
+export * from './updateServerRequestEnabled';
+export * from './updateServerRequestServerName';
export * from './updateSharePermissionRequestV2';
export * from './updateSharePermissionRequestV2ChannelSharePermissions';
export * from './updateSharePermissionRequestV2IsPublic';
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/mcpAuthCallbackParams.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/mcpAuthCallbackParams.ts
new file mode 100644
index 0000000000..d90a15a6be
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/mcpAuthCallbackParams.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+export type McpAuthCallbackParams = {
+ /**
+ * Authorization code from the OAuth provider.
+ */
+ code: string;
+ /**
+ * CSRF state parameter.
+ */
+ state: string;
+};
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/serverResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/serverResponse.ts
new file mode 100644
index 0000000000..7ad53a105a
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/serverResponse.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * An MCP server record as returned by the API.
+ */
+export interface ServerResponse {
+ /** Whether the server has valid stored credentials. */
+ authenticated: boolean;
+ /** Whether the server is enabled for tool use. */
+ enabled: boolean;
+ /** Human-readable server name. */
+ server_name: string;
+ /** The MCP server URL. */
+ url: string;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/startAuthRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/startAuthRequest.ts
new file mode 100644
index 0000000000..ecb0312b19
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/startAuthRequest.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Request body for starting an OAuth authorization flow.
+ */
+export interface StartAuthRequest {
+ /** Human-readable name for the server. */
+ server_name: string;
+ /** The MCP server URL to authorize against. */
+ server_url: string;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/startAuthResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/startAuthResponse.ts
new file mode 100644
index 0000000000..48163ac6d5
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/startAuthResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Response from starting an OAuth authorization flow.
+ */
+export interface StartAuthResponse {
+ /** The OAuth authorization URL to redirect the user to. */
+ authorization_url: string;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/updateServerRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/updateServerRequest.ts
new file mode 100644
index 0000000000..14fe12b884
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/updateServerRequest.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+import type { UpdateServerRequestEnabled } from './updateServerRequestEnabled';
+import type { UpdateServerRequestServerName } from './updateServerRequestServerName';
+
+/**
+ * Request body for updating an MCP server.
+ */
+export interface UpdateServerRequest {
+ /** Enable or disable the server. */
+ enabled?: UpdateServerRequestEnabled;
+ /** New name for the server. */
+ server_name?: UpdateServerRequestServerName;
+ /** The server URL to update. */
+ url: string;
+}
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/updateServerRequestEnabled.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/updateServerRequestEnabled.ts
new file mode 100644
index 0000000000..62668688bd
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/updateServerRequestEnabled.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Enable or disable the server.
+ */
+export type UpdateServerRequestEnabled = boolean | null;
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/updateServerRequestServerName.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/updateServerRequestServerName.ts
new file mode 100644
index 0000000000..133a6308dd
--- /dev/null
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/updateServerRequestServerName.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * New name for the server.
+ */
+export type UpdateServerRequestServerName = string | null;
diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.json
index 7d1f9337c5..df350cb270 100644
--- a/js/app/packages/service-clients/service-cognition/openapi.json
+++ b/js/app/packages/service-clients/service-cognition/openapi.json
@@ -885,6 +885,284 @@
}
}
},
+ "/mcp/servers": {
+ "get": {
+ "tags": ["mcp"],
+ "summary": "List all MCP servers configured for the authenticated user.",
+ "operationId": "list_mcp_servers",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ServerResponse"
+ }
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "put": {
+ "tags": ["mcp"],
+ "summary": "Update an existing MCP server's name or enabled status.",
+ "operationId": "update_mcp_server",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateServerRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ServerResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "tags": ["mcp"],
+ "summary": "Add a new MCP server for the authenticated user.",
+ "operationId": "add_mcp_server",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AddServerRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ServerResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["mcp"],
+ "summary": "Delete an MCP server by URL.",
+ "operationId": "delete_mcp_server",
+ "parameters": [
+ {
+ "name": "url",
+ "in": "query",
+ "description": "The server URL to delete.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/mcp/servers/auth/callback": {
+ "get": {
+ "tags": ["mcp"],
+ "summary": "OAuth callback endpoint — receives code and state from the authorization server.",
+ "operationId": "mcp_auth_callback",
+ "parameters": [
+ {
+ "name": "code",
+ "in": "query",
+ "description": "Authorization code from the OAuth provider.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "state",
+ "in": "query",
+ "description": "CSRF state parameter.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OAuth flow completed successfully"
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/mcp/servers/auth/start": {
+ "post": {
+ "tags": ["mcp"],
+ "summary": "Start the OAuth authorization flow for an MCP server.",
+ "operationId": "start_mcp_auth",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StartAuthRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StartAuthResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/memory": {
"get": {
"tags": ["memory"],
@@ -1097,6 +1375,21 @@
"description": "Ordered from least to most access top -> bottom",
"enum": ["view", "comment", "edit", "owner"]
},
+ "AddServerRequest": {
+ "type": "object",
+ "description": "Request body for adding a new MCP server.",
+ "required": ["url", "server_name"],
+ "properties": {
+ "server_name": {
+ "type": "string",
+ "description": "Human-readable name for the server."
+ },
+ "url": {
+ "type": "string",
+ "description": "The MCP server's streamable HTTP URL."
+ }
+ }
+ },
"AssistantMessagePart": {
"oneOf": [
{
@@ -1997,6 +2290,17 @@
"static_file"
]
},
+ "ErrorResponse": {
+ "type": "object",
+ "description": "A plain old json error response for use with axum.\nyup, thats it.",
+ "required": ["message"],
+ "properties": {
+ "message": {
+ "type": "string",
+ "description": "Message to explain failure"
+ }
+ }
+ },
"ExtractionStatusEnum": {
"oneOf": [
{
@@ -2859,6 +3163,29 @@
}
}
},
+ "ServerResponse": {
+ "type": "object",
+ "description": "An MCP server record as returned by the API.",
+ "required": ["url", "server_name", "enabled", "authenticated"],
+ "properties": {
+ "authenticated": {
+ "type": "boolean",
+ "description": "Whether the server has valid stored credentials."
+ },
+ "enabled": {
+ "type": "boolean",
+ "description": "Whether the server is enabled for tool use."
+ },
+ "server_name": {
+ "type": "string",
+ "description": "Human-readable server name."
+ },
+ "url": {
+ "type": "string",
+ "description": "The MCP server URL."
+ }
+ }
+ },
"SharePermissionV2": {
"type": "object",
"required": ["id", "isPublic", "owner"],
@@ -2895,6 +3222,32 @@
}
}
},
+ "StartAuthRequest": {
+ "type": "object",
+ "description": "Request body for starting an OAuth authorization flow.",
+ "required": ["server_url", "server_name"],
+ "properties": {
+ "server_name": {
+ "type": "string",
+ "description": "Human-readable name for the server."
+ },
+ "server_url": {
+ "type": "string",
+ "description": "The MCP server URL to authorize against."
+ }
+ }
+ },
+ "StartAuthResponse": {
+ "type": "object",
+ "description": "Response from starting an OAuth authorization flow.",
+ "required": ["authorization_url"],
+ "properties": {
+ "authorization_url": {
+ "type": "string",
+ "description": "The OAuth authorization URL to redirect the user to."
+ }
+ }
+ },
"StopChatStreamError": {
"type": "object",
"description": "Error response for the stop endpoint.",
@@ -3071,6 +3424,25 @@
"type": "string",
"enum": ["add", "remove", "replace"]
},
+ "UpdateServerRequest": {
+ "type": "object",
+ "description": "Request body for updating an MCP server.",
+ "required": ["url"],
+ "properties": {
+ "enabled": {
+ "type": ["boolean", "null"],
+ "description": "Enable or disable the server."
+ },
+ "server_name": {
+ "type": ["string", "null"],
+ "description": "New name for the server."
+ },
+ "url": {
+ "type": "string",
+ "description": "The server URL to update."
+ }
+ }
+ },
"UpdateSharePermissionRequestV2": {
"type": "object",
"properties": {
diff --git a/rust/cloud-storage/.sqlx/query-05c2cf10e578df97df70d5b372d6bd4d5a2baf8313799b21496ce399d3612b1b.json b/rust/cloud-storage/.sqlx/query-05c2cf10e578df97df70d5b372d6bd4d5a2baf8313799b21496ce399d3612b1b.json
new file mode 100644
index 0000000000..50082306f7
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-05c2cf10e578df97df70d5b372d6bd4d5a2baf8313799b21496ce399d3612b1b.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM mcp_servers\n WHERE user_id = $1 AND url = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "05c2cf10e578df97df70d5b372d6bd4d5a2baf8313799b21496ce399d3612b1b"
+}
diff --git a/rust/cloud-storage/.sqlx/query-13a6d39ef2b895cae2162fcf65f7f64a5b303859b36186f4106144a2c5cc23ac.json b/rust/cloud-storage/.sqlx/query-13a6d39ef2b895cae2162fcf65f7f64a5b303859b36186f4106144a2c5cc23ac.json
new file mode 100644
index 0000000000..6792d184f7
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-13a6d39ef2b895cae2162fcf65f7f64a5b303859b36186f4106144a2c5cc23ac.json
@@ -0,0 +1,46 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT user_id, url, server_name, credentials, enabled\n FROM mcp_servers\n WHERE user_id = $1\n ORDER BY created_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "url",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "server_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "credentials",
+ "type_info": "Bytea"
+ },
+ {
+ "ordinal": 4,
+ "name": "enabled",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ false
+ ]
+ },
+ "hash": "13a6d39ef2b895cae2162fcf65f7f64a5b303859b36186f4106144a2c5cc23ac"
+}
diff --git a/rust/cloud-storage/.sqlx/query-1fc6d4133d6252a01a56005faa3e7244ab1debf1731781813995f3be3075d9f1.json b/rust/cloud-storage/.sqlx/query-1fc6d4133d6252a01a56005faa3e7244ab1debf1731781813995f3be3075d9f1.json
new file mode 100644
index 0000000000..813b01d6d0
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-1fc6d4133d6252a01a56005faa3e7244ab1debf1731781813995f3be3075d9f1.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO mcp_servers (user_id, url, server_name, credentials, enabled)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (user_id, url) DO UPDATE\n SET server_name = EXCLUDED.server_name,\n credentials = EXCLUDED.credentials,\n enabled = EXCLUDED.enabled,\n updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Bytea",
+ "Bool"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1fc6d4133d6252a01a56005faa3e7244ab1debf1731781813995f3be3075d9f1"
+}
diff --git a/rust/cloud-storage/.sqlx/query-60160128531d4bd143edb6e3af105954c5f749b5a76592d8ba8bd78d3ed410cc.json b/rust/cloud-storage/.sqlx/query-60160128531d4bd143edb6e3af105954c5f749b5a76592d8ba8bd78d3ed410cc.json
new file mode 100644
index 0000000000..07556c0356
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-60160128531d4bd143edb6e3af105954c5f749b5a76592d8ba8bd78d3ed410cc.json
@@ -0,0 +1,47 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT user_id, url, server_name, credentials, enabled\n FROM mcp_servers\n WHERE user_id = $1 AND url = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "url",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "server_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "credentials",
+ "type_info": "Bytea"
+ },
+ {
+ "ordinal": 4,
+ "name": "enabled",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ false
+ ]
+ },
+ "hash": "60160128531d4bd143edb6e3af105954c5f749b5a76592d8ba8bd78d3ed410cc"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index fff04d64f7..336c662233 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -8,6 +8,16 @@ version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627"
+[[package]]
+name = "aead"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
+dependencies = [
+ "crypto-common 0.1.6",
+ "generic-array",
+]
+
[[package]]
name = "aes"
version = "0.8.4"
@@ -19,6 +29,20 @@ dependencies = [
"cpufeatures 0.2.17",
]
+[[package]]
+name = "aes-gcm"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
+dependencies = [
+ "aead",
+ "aes",
+ "cipher",
+ "ctr",
+ "ghash",
+ "subtle",
+]
+
[[package]]
name = "ahash"
version = "0.8.11"
@@ -149,6 +173,7 @@ dependencies = [
"axum-macros",
"futures",
"macro_user_id",
+ "non_empty",
"schemars",
"serde",
"serde_json",
@@ -2711,6 +2736,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
+ "rand_core 0.6.4",
"typenum",
]
@@ -2759,6 +2785,15 @@ dependencies = [
"syn 2.0.98",
]
+[[package]]
+name = "ctr"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
+dependencies = [
+ "cipher",
+]
+
[[package]]
name = "ctutils"
version = "0.4.2"
@@ -3182,9 +3217,11 @@ dependencies = [
"macro_project_utils",
"macro_user_id",
"macro_uuid",
+ "mcp_client",
"memory",
"model",
"model-entity",
+ "model-error-response",
"model_notifications",
"models_dcs",
"models_opensearch",
@@ -4652,6 +4689,16 @@ dependencies = [
"wasip3",
]
+[[package]]
+name = "ghash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
+dependencies = [
+ "opaque-debug",
+ "polyval",
+]
+
[[package]]
name = "gif"
version = "0.14.0"
@@ -6671,6 +6718,34 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "mcp_client"
+version = "0.1.0"
+dependencies = [
+ "aes-gcm",
+ "ai",
+ "ai_toolset",
+ "anyhow",
+ "async-openai",
+ "axum",
+ "base64 0.22.1",
+ "futures",
+ "macro_user_id",
+ "model-error-response",
+ "model_user",
+ "oauth2",
+ "redis",
+ "reqwest 0.13.3",
+ "rmcp",
+ "schemars",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "thiserror 2.0.17",
+ "tracing",
+ "utoipa",
+]
+
[[package]]
name = "mcp_service"
version = "0.1.0"
@@ -7669,6 +7744,25 @@ dependencies = [
"libm",
]
+[[package]]
+name = "oauth2"
+version = "5.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d"
+dependencies = [
+ "base64 0.22.1",
+ "chrono",
+ "getrandom 0.2.15",
+ "http 1.3.1",
+ "rand 0.8.5",
+ "serde",
+ "serde_json",
+ "serde_path_to_error",
+ "sha2 0.10.8",
+ "thiserror 1.0.69",
+ "url",
+]
+
[[package]]
name = "objc2"
version = "0.6.4"
@@ -7838,6 +7932,12 @@ dependencies = [
"portable-atomic",
]
+[[package]]
+name = "opaque-debug"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+
[[package]]
name = "opensearch"
version = "2.3.0"
@@ -8489,6 +8589,18 @@ dependencies = [
"miniz_oxide",
]
+[[package]]
+name = "polyval"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash",
+]
+
[[package]]
name = "portable-atomic"
version = "1.13.1"
@@ -9415,9 +9527,9 @@ dependencies = [
[[package]]
name = "rmcp"
-version = "1.2.0"
+version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ba6b9d2f0efe2258b23767f1f9e0054cfbcac9c2d6f81a031214143096d7864f"
+checksum = "e12ca9067b5ebfbd5b3fcdc4acfceb81aa7d5ab2a879dff7cb75d22434276aad"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -9427,9 +9539,11 @@ dependencies = [
"http 1.3.1",
"http-body 1.0.1",
"http-body-util",
+ "oauth2",
"pastey 0.2.1",
"pin-project-lite",
"rand 0.10.0",
+ "reqwest 0.13.3",
"rmcp-macros",
"schemars",
"serde",
@@ -9441,14 +9555,15 @@ dependencies = [
"tokio-util",
"tower-service",
"tracing",
+ "url",
"uuid",
]
[[package]]
name = "rmcp-macros"
-version = "1.2.0"
+version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ab9d95d7ed26ad8306352b0d5f05b593222b272790564589790d210aa15caa9e"
+checksum = "7caa6743cc0888e433105fe1bc551a7f607940b126a37bc97b478e86064627eb"
dependencies = [
"darling 0.23.0",
"proc-macro2",
@@ -11939,6 +12054,16 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+[[package]]
+name = "universal-hash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
+dependencies = [
+ "crypto-common 0.1.6",
+ "subtle",
+]
+
[[package]]
name = "unsynn"
version = "0.3.0"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 34b8611478..4f21d0eadd 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -76,6 +76,7 @@ members = [
"macro_sha_count_client",
"macro_uuid",
"mcp_auth_proxy",
+ "mcp_client",
"mcp_service",
"memory",
"mention_utils",
@@ -203,6 +204,7 @@ rand = "0.9.0"
recursion = "0.5.4"
redis = "1.0.3"
regex = "1.11.1"
+rmcp = "1.6.0"
reqwest = { version = "0.13", features = ["form", "hickory-dns", "json"] }
rootcause = { version = "0.12" }
schemars = { version = "1.0.4", features = ["chrono04", "uuid1"] }
diff --git a/rust/cloud-storage/ai/src/lib.rs b/rust/cloud-storage/ai/src/lib.rs
index 05195a0dcb..c0997b02e7 100644
--- a/rust/cloud-storage/ai/src/lib.rs
+++ b/rust/cloud-storage/ai/src/lib.rs
@@ -1,7 +1,7 @@
pub mod chat_completion;
pub mod chat_stream;
pub mod model_selection;
-mod openai_toolset;
+pub mod openai_toolset;
pub mod prompts;
pub mod simple_completion;
pub mod structured_output_v2;
diff --git a/rust/cloud-storage/ai/src/openai_toolset.rs b/rust/cloud-storage/ai/src/openai_toolset.rs
index a3f1aedbdf..38802b159e 100644
--- a/rust/cloud-storage/ai/src/openai_toolset.rs
+++ b/rust/cloud-storage/ai/src/openai_toolset.rs
@@ -3,7 +3,7 @@
//! This module provides conversions to OpenAI's tool types for use with
//! the `async-openai` crate.
-use ai_toolset::ToolSet;
+use ai_toolset::ToolCollection;
use ai_toolset::tool_object::ToolObject;
use async_openai::types::chat::{ChatCompletionTool, ChatCompletionTools, FunctionObject};
@@ -27,7 +27,7 @@ pub trait OpenAIToolSetExt {
fn openai_chatcompletion_toolset(&self) -> Vec<ChatCompletionTools>;
}
-impl<T> OpenAIToolSetExt for ToolSet<ToolObject<T>> {
+impl<T> OpenAIToolSetExt for ToolCollection<ToolObject<T>> {
fn openai_chatcompletion_toolset(&self) -> Vec<ChatCompletionTools> {
self.tools
.values()
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/ai_client.rs b/rust/cloud-storage/ai/src/tool/tool_loop/ai_client.rs
index abb048550a..649507a9aa 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/ai_client.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/ai_client.rs
@@ -1,25 +1,26 @@
use super::chat::Chat;
-use crate::tool::types::AsyncToolSet;
+use crate::openai_toolset::OpenAIToolSetExt;
+use crate::tool::types::{AsyncToolCollection, ToolSet};
use crate::types::AnthropicClient;
use crate::types::ExtendedClient;
use anthropic::openai::request::{AnthropicRequestExtension, AnthropicRequestExtensions};
use std::sync::Arc;
-pub struct ToolLoop<I, T>
+pub struct ToolLoop<I, T, S = AsyncToolCollection<T>>
where
I: ExtendedClient + Clone + Send + Sync,
T: Clone + Send + Sync,
{
client: I,
context: T,
- toolset: Arc<AsyncToolSet<T>>,
+ toolset: Arc<S>,
}
-impl<T> ToolLoop<AnthropicClient, T>
+impl<T, S> ToolLoop<AnthropicClient, T, S>
where
T: Clone + Send + Sync,
{
- pub fn new(toolset: Arc<AsyncToolSet<T>>, context: T) -> Self {
+ pub fn new(toolset: Arc<S>, context: T) -> Self {
let extensions = AnthropicRequestExtensions(vec![
AnthropicRequestExtension::WebSearchTool,
AnthropicRequestExtension::FetchTool,
@@ -34,12 +35,13 @@ where
}
}
-impl<I, T> ToolLoop<I, T>
+impl<I, T, S> ToolLoop<I, T, S>
where
I: ExtendedClient + Clone + Send + Sync,
T: Clone + Send + Sync,
+ S: ToolSet<T> + OpenAIToolSetExt,
{
- pub fn chat(&self) -> Chat<I, T> {
+ pub fn chat(&self) -> Chat<I, T, S> {
Chat::new(
self.client.clone(),
self.toolset.clone(),
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/chat/agent.rs b/rust/cloud-storage/ai/src/tool/tool_loop/chat/agent.rs
index db30af78ef..c9a223b6dd 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/chat/agent.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/chat/agent.rs
@@ -1,9 +1,9 @@
use super::MAX_RECURSIONS;
use crate::openai_toolset::OpenAIToolSetExt;
+use crate::tool::types::{ChatCompletionStream, ExtendedPartStream, PartOrExt, ToolResponse};
use crate::tool::types::{
- AsyncToolSet, PartialToolCall, RequestContext, StreamPart, ToolCall, ToolResult,
+ PartialToolCall, RequestContext, StreamPart, ToolCall, ToolResult, ToolSet,
};
-use crate::tool::types::{ChatCompletionStream, ExtendedPartStream, PartOrExt, ToolResponse};
use crate::types::openai::message::convert_message;
use crate::types::traits::{ExtendedOpenAIStream, ExtendedOpenAIStreamItem};
use crate::types::{ChatCompletionRequest, ChatMessage, ChatMessages};
@@ -24,13 +24,13 @@ struct ProcessedStream {
pub tool_responses: Vec<ToolResponse>,
}
-pub struct Chat<I, T>
+pub struct Chat<I, T, S>
where
I: ExtendedClient + Send + Sync,
T: Clone + Send + Sync + 'static,
{
client: I,
- toolset: Arc<AsyncToolSet<T>>,
+ toolset: Arc<S>,
request: CreateChatCompletionRequest,
pub(crate) messages: Vec<ChatCompletionRequestMessage>,
context: T,
@@ -39,12 +39,13 @@ where
user_id: String,
}
-impl<I, T> Chat<I, T>
+impl<I, T, S> Chat<I, T, S>
where
I: ExtendedClient + Send + Sync,
T: Clone + Send + Sync,
+ S: ToolSet<T> + OpenAIToolSetExt,
{
- pub fn new(client: I, toolset: Arc<AsyncToolSet<T>>, context: T) -> Chat<I, T> {
+ pub fn new(client: I, toolset: Arc<S>, context: T) -> Chat<I, T, S> {
Chat {
client,
toolset,
@@ -84,10 +85,11 @@ where
}
}
-impl<I, T> Chat<I, T>
+impl<I, T, S> Chat<I, T, S>
where
I: ExtendedClient + Send + Sync,
T: Clone + Send + Sync,
+ S: ToolSet<T> + OpenAIToolSetExt,
{
#[tracing::instrument(err, skip_all)]
async fn make_chat_completion_stream(
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rs b/rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rs
index 5cdcc8b06c..c839479a7a 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/chat/test.rs
@@ -1,7 +1,7 @@
use super::*;
use crate::openai_toolset::OpenAIToolSetExt;
use crate::tool::types::{
- AsyncToolSet, PartialToolCall, RequestContext, StreamPart, ToolCall, ToolResult,
+ AsyncToolCollection, PartialToolCall, RequestContext, StreamPart, ToolCall, ToolResult, ToolSet,
};
use crate::tool::types::{ChatCompletionStream, ExtendedPartStream, PartOrExt, ToolResponse};
use crate::types::noop::NoOpClient;
@@ -39,7 +39,7 @@ where
T: Clone + Send + Sync + 'static,
{
client: I,
- toolset: Arc<AsyncToolSet<T>>,
+ toolset: Arc<AsyncToolCollection<T>>,
request: CreateChatCompletionRequest,
messages: Vec<ChatCompletionRequestMessage>,
context: T,
@@ -54,7 +54,7 @@ where
I: ExtendedClient + Send + Sync,
T: Clone + Send + Sync,
{
- pub fn new(client: I, toolset: Arc<AsyncToolSet<T>>, context: T) -> Chat<I, T> {
+ pub fn new(client: I, toolset: Arc<AsyncToolCollection<T>>, context: T) -> Chat<I, T> {
Chat {
client,
toolset,
@@ -410,7 +410,7 @@ where
fn create_mock_chat() -> Chat<NoOpClient, String> {
let client = NoOpClient;
- let toolset = Arc::new(AsyncToolSet::new());
+ let toolset = Arc::new(AsyncToolCollection::new());
Chat::new(client, toolset, "test_context".to_string())
}
diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs b/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs
index 686d4f76c9..26dea82ede 100644
--- a/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs
+++ b/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs
@@ -8,14 +8,14 @@
//!
//! ```rust,ignore
//! use ai::tool::tool_loop::cli::Cli;
-//! use ai::tool::{AsyncToolSet, RequestContext};
+//! use ai::tool::{AsyncToolCollection, RequestContext};
//! use ai::types::Model;
//! use macro_user_id::user_id::MacroUserIdStr;
//! use std::sync::Arc;
//!
//! #[tokio::main]
//! async fn main() {
-//! let toolset = AsyncToolSet::new()
+//! let toolset = AsyncToolCollection::new()
//! .add_tool::<MyTool>()
//! .expect("failed to add tool");
//!
@@ -43,9 +43,10 @@
//! }
//! ```
+use crate::openai_toolset::OpenAIToolSetExt;
use crate::prompts::CLI_PROMPT;
use crate::tool::ToolLoop;
-use crate::tool::types::{AsyncToolSet, RequestContext, StreamPart, ToolResponse};
+use crate::tool::types::{AsyncToolCollection, RequestContext, StreamPart, ToolResponse, ToolSet};
use crate::types::{ChatMessage, MessageBuilder, Model, RequestBuilder, Role};
use futures::stream::StreamExt;
use macro_user_id::user_id::MacroUserIdStr;
@@ -56,12 +57,12 @@ use std::sync::Arc;
///
/// This struct wraps the tool loop and provides an interactive readline-style
/// interface for multi-turn conversations with tool support.
-pub struct Cli<T, F>
+pub struct Cli<T, F, S = AsyncToolCollection<T>>
where
T: Clone + Send + Sync + 'static,
F: Fn() -> RequestContext,
{
- toolset: AsyncToolSet<T>,
+ toolset: S,
service_context: T,
system_prompt: String,
model: Model,
@@ -71,7 +72,7 @@ where
impl Default for Cli<(), fn() -> RequestContext> {
fn default() -> Self {
Self {
- toolset: AsyncToolSet::new(),
+ toolset: AsyncToolCollection::new(),
service_context: (),
system_prompt: CLI_PROMPT.to_string(),
model: Model::Claude45Opus,
@@ -82,10 +83,11 @@ impl Default for Cli<(), fn() -> RequestContext> {
}
}
-impl<T, F> Cli<T, F>
+impl<T, F, S> Cli<T, F, S>
where
T: Clone + Send + Sync + 'static,
F: Fn() -> RequestContext,
+ S: ToolSet<T> + OpenAIToolSetExt,
{
/// Create a new CLI with the given configuration.
///
@@ -97,7 +99,7 @@ where
/// * `model` - The model to use for completions
/// * `request_context_fn` - A function that creates a request context for each message
pub fn new(
- toolset: AsyncToolSet<T>,
+ toolset: S,
service_context: T,
system_prompt: impl Into<String>,
model: Model,
@@ -125,18 +127,15 @@ where
pub async fn run(self) {
// Print startup info
println!("Model: {}", self.model);
- let tool_names: Vec<&String> = self.toolset.tools.keys().collect();
+ let tool_names: Vec<String> = self
+ .toolset
+ .request_schemas()
+ .map(|schemas| schemas.into_iter().map(|s| s.name).collect())
+ .unwrap_or_default();
if tool_names.is_empty() {
println!("Tools: (none)");
} else {
- println!(
- "Tools: {}",
- tool_names
- .into_iter()
- .cloned()
- .collect::<Vec<_>>()
- .join(", ")
- );
+ println!("Tools: {}", tool_names.join(", "));
}
println!("---");
diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rs
index 569d49089c..091d6f1005 100644
--- a/rust/cloud-storage/ai_tools/src/build_context.rs
+++ b/rust/cloud-storage/ai_tools/src/build_context.rs
@@ -267,7 +267,7 @@ pub async fn build_tool_service_context_from_env(
let chat_repo = chat::outbound::postgres::PgChatRepo::new(pool.clone());
let chat_service = chat::domain::service::ChatServiceImpl::new(
chat_repo,
- Arc::new(ai_toolset::AsyncToolSet::new()),
+ Arc::new(ai_toolset::AsyncToolCollection::new()),
(),
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
entity_access_management::outbound::PgRepository::new(pool.clone()),
diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rs
index c495ce6585..10b6ce090e 100644
--- a/rust/cloud-storage/ai_tools/src/lib.rs
+++ b/rust/cloud-storage/ai_tools/src/lib.rs
@@ -1,6 +1,6 @@
#![recursion_limit = "256"]
-use ai_toolset::AsyncToolSet;
+use ai_toolset::AsyncToolCollection;
use ai_toolset::schema::{CombinedToolSchemas, ToolSchemaGenerator};
mod build_context;
pub mod prompts;
@@ -26,7 +26,7 @@ pub use build_context::build_tool_service_context_from_env;
pub use search::search_toolset;
pub use tool_context::*;
-pub type AiToolSet = AsyncToolSet<ToolServiceContext>;
+pub type AiToolSet = AsyncToolCollection<ToolServiceContext>;
pub struct ToolSetWithPrompt {
pub toolset: Arc<AiToolSet>,
@@ -49,7 +49,7 @@ impl ToolSchemaGenerator for ToolSetWithPrompt {
/// Toolset available to subagents — everything except email and the Subagent
/// tool itself (subagents cannot create subagents).
pub(crate) fn subagent_toolset() -> AiToolSet {
- AsyncToolSet::new()
+ AsyncToolCollection::new()
.add_toolset(search_toolset())
.add_tool::<ListEntities, SoupToolContext<ToolSoupService, ToolEmailService>>()
.add_subtoolset::<ToolDocumentToolContext>(document_toolset())
@@ -96,6 +96,6 @@ pub fn mcp_tools() -> ToolSetWithPrompt {
pub fn no_tools() -> ToolSetWithPrompt {
ToolSetWithPrompt {
prompt: prompts::BASE_PROMPT,
- toolset: Arc::new(AsyncToolSet::new()),
+ toolset: Arc::new(AsyncToolCollection::new()),
}
}
diff --git a/rust/cloud-storage/ai_tools/src/search/mod.rs b/rust/cloud-storage/ai_tools/src/search/mod.rs
index 48fbf2e7ed..5cb21a2338 100644
--- a/rust/cloud-storage/ai_tools/src/search/mod.rs
+++ b/rust/cloud-storage/ai_tools/src/search/mod.rs
@@ -1,11 +1,11 @@
use crate::AiToolSet;
-use ai_toolset::AsyncToolSet;
+use ai_toolset::AsyncToolCollection;
mod search_service;
pub mod web;
pub fn search_toolset() -> AiToolSet {
- AsyncToolSet::new()
+ AsyncToolCollection::new()
.add_tool::<search_service::name::NameSearch, _>()
.add_tool::<search_service::content::ContentSearch, _>()
}
diff --git a/rust/cloud-storage/ai_toolset/Cargo.toml b/rust/cloud-storage/ai_toolset/Cargo.toml
index 5bae0c795f..903c66a47d 100644
--- a/rust/cloud-storage/ai_toolset/Cargo.toml
+++ b/rust/cloud-storage/ai_toolset/Cargo.toml
@@ -17,3 +17,4 @@ macro_user_id = { path = "../macro_user_id" }
axum = { workspace = true }
axum-macros = { workspace = true }
tracing = { workspace = true }
+non_empty = { path = "../non_empty" }
diff --git a/rust/cloud-storage/ai_toolset/src/schema/generate.rs b/rust/cloud-storage/ai_toolset/src/schema/generate.rs
index e37c466814..0a8d86cdce 100644
--- a/rust/cloud-storage/ai_toolset/src/schema/generate.rs
+++ b/rust/cloud-storage/ai_toolset/src/schema/generate.rs
@@ -1,4 +1,4 @@
-use crate::AsyncToolSet;
+use crate::AsyncToolCollection;
use schemars::Schema;
use schemars::transform::Transform;
use serde::{Deserialize, Serialize};
@@ -282,7 +282,7 @@ impl CombinedToolSchemasBuilder {
}
}
-impl<Context> ToolSchemaGenerator for AsyncToolSet<Context> {
+impl<Context> ToolSchemaGenerator for AsyncToolCollection<Context> {
fn generate_schemas(&self) -> ToolSchemas {
let schemas = self
.tools
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/mod.rs b/rust/cloud-storage/ai_toolset/src/toolset/mod.rs
index 8a3f835256..6a504d01e7 100644
--- a/rust/cloud-storage/ai_toolset/src/toolset/mod.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/mod.rs
@@ -1,6 +1,8 @@
//! Toolset management for organizing and invoking AI tools.
pub mod tool_object;
+mod traits;
mod types;
+pub use traits::*;
pub use types::*;
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/traits.rs b/rust/cloud-storage/ai_toolset/src/toolset/traits.rs
new file mode 100644
index 0000000000..15d6878bd1
--- /dev/null
+++ b/rust/cloud-storage/ai_toolset/src/toolset/traits.rs
@@ -0,0 +1,59 @@
+//! The core ToolSet trait implemented by the ToolSet and AsyncToolset
+use crate::toolset::types::{RequestSchema, ToolInfo};
+use crate::{AsyncToolCollection, RequestContext, ToolResult, ToolSetError};
+use std::pin::Pin;
+
+/// An object with a set of tools
+pub trait ToolSet<Context>: Send + Sync {
+ /// Try to call a tool indexed by name with the provided raw json
+ fn try_tool_call<'a>(
+ &'a self,
+ context: Context,
+ request_context: RequestContext,
+ tool_name: &'a str,
+ json: &'a serde_json::Value,
+ ) -> Pin<
+ Box<dyn Future<Output = Result<ToolResult<serde_json::Value>, ToolSetError>> + 'a + Send>,
+ >;
+
+ /// Returns the input schemas for all tools in the toolset, or `None` if the toolset is empty.
+ fn request_schemas(&self) -> Option<Vec<RequestSchema>>;
+
+ /// Dynamic routers use this to demangle tool names for frontend consumption
+ fn routing_description<'a>(&'a self, _tool_name: &'a str) -> Option<ToolInfo> {
+ None
+ }
+}
+
+impl<Context> ToolSet<Context> for AsyncToolCollection<Context>
+where
+ Context: Send + Sync + 'static,
+{
+ fn try_tool_call<'a>(
+ &'a self,
+ context: Context,
+ request_context: RequestContext,
+ tool_name: &'a str,
+ json: &'a serde_json::Value,
+ ) -> Pin<
+ Box<dyn Future<Output = Result<ToolResult<serde_json::Value>, ToolSetError>> + 'a + Send>,
+ > {
+ Box::pin(self.try_tool_call_internal(context, request_context, tool_name, json))
+ }
+
+ fn request_schemas(&self) -> Option<Vec<RequestSchema>> {
+ let schemas = self
+ .tools
+ .values()
+ .map(|tool| RequestSchema {
+ name: tool.name.clone(),
+ schema: tool.input_schema.clone().into(),
+ })
+ .collect::<Vec<_>>();
+ if schemas.is_empty() {
+ None
+ } else {
+ Some(schemas)
+ }
+ }
+}
diff --git a/rust/cloud-storage/ai_toolset/src/toolset/types.rs b/rust/cloud-storage/ai_toolset/src/toolset/types.rs
index ce8f06f730..714c47a68d 100644
--- a/rust/cloud-storage/ai_toolset/src/toolset/types.rs
+++ b/rust/cloud-storage/ai_toolset/src/toolset/types.rs
@@ -9,6 +9,18 @@ use serde::de::Deserialize;
use std::collections::BTreeMap;
use thiserror::Error;
+/// some tools need additional information
+#[derive(Debug)]
+pub enum ToolInfo {
+ /// An external (MCP) tool call
+ ExternalTool {
+ /// The name of the external service (MCP server)
+ service_name: String,
+ /// the name of the tool
+ tool_name: String,
+ },
+}
+
/// Error type for failures when creating or adding tools to a toolset.
#[derive(Debug, Error)]
pub enum ToolSetCreationError {
@@ -32,9 +44,17 @@ pub enum ToolSetError {
}
/// Type alias for a toolset containing asynchronous tools.
-pub type AsyncToolSet<ToolSetContext> = ToolSet<AsyncToolObject<ToolSetContext>>;
+pub type AsyncToolCollection<ToolSetContext> = ToolCollection<AsyncToolObject<ToolSetContext>>;
+
+/// Schema for a tool's input, used when building provider requests.
+pub struct RequestSchema {
+ /// The name of the tool.
+ pub name: String,
+ /// The JSON schema for the tool's input parameters.
+ pub schema: Schema,
+}
-/// Represents the schema information for a tool.
+/// Represents the full schema information for a tool.
pub struct ToolSchema {
/// The name of the tool.
pub name: String,
@@ -60,7 +80,7 @@ impl ToolSchema {
/// `ToolSet` manages a set of tools, allowing you to add tools, merge toolsets,
/// and invoke tools by name with JSON input.
#[derive(Default)]
-pub struct ToolSet<T> {
+pub struct ToolCollection<T> {
/// The tools in this toolset, keyed by name.
/// This includes type-erased user tools
pub tools: BTreeMap<String, T>,
@@ -68,7 +88,7 @@ pub struct ToolSet<T> {
pub user_tools: BTreeMap<String, T>,
}
-impl<T> ToolSet<T> {
+impl<T> ToolCollection<T> {
/// Creates a new empty toolset.
pub fn new() -> Self {
Self {
@@ -78,11 +98,11 @@ impl<T> ToolSet<T> {
}
}
-impl<T> ToolSet<T> {
+impl<T> ToolCollection<T> {
/// Merges another toolset into this one.
///
/// Returns an error if any tool names conflict between the two toolsets.
- pub fn add_toolset(mut self, toolset: ToolSet<T>) -> Self {
+ pub fn add_toolset(mut self, toolset: ToolCollection<T>) -> Self {
for (name, _) in toolset.tools.iter() {
if self.tools.contains_key(name) {
panic!("{}", ToolSetCreationError::NameConflict(name.clone()));
@@ -99,7 +119,7 @@ impl<T> ToolSet<T> {
}
}
-impl<ToolSetContext> AsyncToolSet<ToolSetContext>
+impl<ToolSetContext> AsyncToolCollection<ToolSetContext>
where
ToolSetContext: Sync + Send + 'static,
{
@@ -160,7 +180,7 @@ where
///
/// Returns an error if the tool is not found or if deserialization fails.
#[tracing::instrument(err, skip(self, context, request_context))]
- pub async fn try_tool_call(
+ pub(crate) async fn try_tool_call_internal(
&self,
context: ToolSetContext,
request_context: RequestContext,
@@ -178,7 +198,7 @@ where
Ok(tool.call(context, request_context).await)
}
- /// this isn't called in the tool loop it's calle by the user-facing API
+ /// this isn't called in the tool loop it's called by the user-facing API
#[tracing::instrument(err, skip(self, context, request_context))]
pub async fn try_user_tool_call(
&self,
@@ -269,7 +289,7 @@ where
/// assert!(parent_toolset.tools.contains_key("SubTool"));
/// ```
#[tracing::instrument(skip_all)]
- pub fn add_subtoolset<SubContext>(mut self, subtoolset: AsyncToolSet<SubContext>) -> Self
+ pub fn add_subtoolset<SubContext>(mut self, subtoolset: AsyncToolCollection<SubContext>) -> Self
where
SubContext: FromRef<ToolSetContext> + Send + Sync + 'static,
{
diff --git a/rust/cloud-storage/call/src/inbound/toolset/mod.rs b/rust/cloud-storage/call/src/inbound/toolset/mod.rs
index b3deb0ae69..2be2d0b78f 100644
--- a/rust/cloud-storage/call/src/inbound/toolset/mod.rs
+++ b/rust/cloud-storage/call/src/inbound/toolset/mod.rs
@@ -7,7 +7,7 @@ mod read_call_record;
mod test;
use crate::domain::ports::{CallRecordQueryService, CallService};
-use ai::tool::AsyncToolSet;
+use ai::tool::AsyncToolCollection;
use entity_access::domain::ports::EntityAccessService;
use std::sync::Arc;
@@ -61,13 +61,13 @@ where
}
/// Create a call toolset.
-pub fn call_toolset<CSvc, QSvc, ESvc>() -> AsyncToolSet<CallToolContext<CSvc, QSvc, ESvc>>
+pub fn call_toolset<CSvc, QSvc, ESvc>() -> AsyncToolCollection<CallToolContext<CSvc, QSvc, ESvc>>
where
CSvc: CallService,
QSvc: CallRecordQueryService,
ESvc: EntityAccessService,
{
- AsyncToolSet::new()
+ AsyncToolCollection::new()
.add_tool::<ListCallRecords, CallToolContext<CSvc, QSvc, ESvc>>()
.add_tool::<ReadCallRecord, CallToolContext<CSvc, QSvc, ESvc>>()
}
diff --git a/rust/cloud-storage/channels/src/inbound/toolset/mod.rs b/rust/cloud-storage/channels/src/inbound/toolset/mod.rs
index 6415b35ae9..5aecdca264 100644
--- a/rust/cloud-storage/channels/src/inbound/toolset/mod.rs
+++ b/rust/cloud-storage/channels/src/inbound/toolset/mod.rs
@@ -9,7 +9,7 @@ mod types;
mod test;
use crate::domain::ports::ChannelMessagesService;
-use ai::tool::{AsyncToolSet, RequestContext, ToolCallError};
+use ai::tool::{AsyncToolCollection, RequestContext, ToolCallError};
use entity_access::domain::{
models::{AccessError, AccessLevel, EntityType},
ports::EntityAccessService,
@@ -99,12 +99,12 @@ fn channel_access_error(err: AccessError) -> ToolCallError {
}
/// Create the channel AI toolset.
-pub fn channel_toolset<Svc, AccessSvc>() -> AsyncToolSet<ChannelToolContext<Svc, AccessSvc>>
+pub fn channel_toolset<Svc, AccessSvc>() -> AsyncToolCollection<ChannelToolContext<Svc, AccessSvc>>
where
Svc: ChannelMessagesService,
AccessSvc: EntityAccessService,
{
- AsyncToolSet::new()
+ AsyncToolCollection::new()
.add_tool::<ReadChannelMessages, ChannelToolContext<Svc, AccessSvc>>()
.add_tool::<ReadChannelMessageContext, ChannelToolContext<Svc, AccessSvc>>()
.add_tool::<ReadChannelThread, ChannelToolContext<Svc, AccessSvc>>()
diff --git a/rust/cloud-storage/chat/src/domain/service/chat.rs b/rust/cloud-storage/chat/src/domain/service/chat.rs
index 48a4c6c847..e4eb4d60a1 100644
--- a/rust/cloud-storage/chat/src/domain/service/chat.rs
+++ b/rust/cloud-storage/chat/src/domain/service/chat.rs
@@ -5,7 +5,7 @@ use crate::domain::{
ports::{ChatRepo, ChatService},
};
use ai::types::{AssistantMessagePart, ChatMessageContent};
-use ai_toolset::{AsyncToolSet, RequestContext, tool_object::UserToolResponse};
+use ai_toolset::{AsyncToolCollection, RequestContext, tool_object::UserToolResponse};
use entity_access::domain::models::{
EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
};
@@ -22,7 +22,7 @@ where
ToolSetContext: Clone + Send + Sync + 'static,
{
// toolset should be replaced with trait;
- toolset: Arc<AsyncToolSet<ToolSetContext>>,
+ toolset: Arc<AsyncToolCollection<ToolSetContext>>,
context: ToolSetContext,
repo: R,
entity_access_management_service: Eam,
@@ -36,7 +36,7 @@ where
/// Create a new [`ChatServiceImpl`] wrapping the given repo and tool executor.
pub fn new(
repo: R,
- toolset: Arc<AsyncToolSet<ToolSetContext>>,
+ toolset: Arc<AsyncToolCollection<ToolSetContext>>,
context: ToolSetContext,
entity_access_management_service: Eam,
) -> Self {
diff --git a/rust/cloud-storage/chat/src/inbound/toolset/mod.rs b/rust/cloud-storage/chat/src/inbound/toolset/mod.rs
index ba72369764..4e761e71e7 100644
--- a/rust/cloud-storage/chat/src/inbound/toolset/mod.rs
+++ b/rust/cloud-storage/chat/src/inbound/toolset/mod.rs
@@ -6,7 +6,7 @@ mod read_chat;
mod test;
use crate::domain::ports::ChatService;
-use ai::tool::AsyncToolSet;
+use ai::tool::AsyncToolCollection;
use entity_access::domain::ports::EntityAccessService;
use read_chat::ReadChat;
use std::sync::Arc;
@@ -51,10 +51,10 @@ where
}
/// Create a chat toolset.
-pub fn chat_toolset<CSvc, ESvc>() -> AsyncToolSet<ChatToolContext<CSvc, ESvc>>
+pub fn chat_toolset<CSvc, ESvc>() -> AsyncToolCollection<ChatToolContext<CSvc, ESvc>>
where
CSvc: ChatService,
ESvc: EntityAccessService,
{
- AsyncToolSet::new().add_tool::<ReadChat, ChatToolContext<CSvc, ESvc>>()
+ AsyncToolCollection::new().add_tool::<ReadChat, ChatToolContext<CSvc, ESvc>>()
}
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index 94d1655992..8d06862258 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -77,6 +77,8 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea
macro_project_utils = { path = "../macro_project_utils" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
+mcp_client = { path = "../mcp_client" }
+model-error-response = { path = "../model-error-response" }
memory = { path = "../memory" }
model = { path = "../model" }
model-entity = { path = "../model-entity" }
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
index 80f13ea229..310d4648cf 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
@@ -54,6 +54,15 @@ pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsQueue>;
pub type DcsMemoryService =
memory::domain::service::MemoryServiceImpl<memory::outbound::pg_memory_repo::PgMemoryRepo>;
+/// Concrete MCP router state for DCS.
+pub type DcsMcpRouterState = mcp_client::inbound::McpRouterState<
+ mcp_client::outbound::pg_server_repo::PgServerRepo,
+ mcp_client::domain::service::OAuthService<
+ mcp_client::outbound::pg_server_repo::PgServerRepo,
+ mcp_client::outbound::redis_state_store::RedisOAuthStateStore,
+ >,
+>;
+
#[derive(Clone, FromRef)]
pub struct ApiContext {
pub db: PgPool,
@@ -81,6 +90,7 @@ pub struct ApiContext {
pub entity_access_service: Arc<DcsEntityAccessService>,
pub message_service: Arc<DcsMessageService>,
pub ai_stream_registry: AiStreamRegistry,
+ pub mcp_state: DcsMcpRouterState,
}
pub static GLOBAL_CONTEXT: OnceLock<ApiContext> = OnceLock::new();
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index 7d6dfe2ebd..aea4b95d78 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -295,7 +295,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(
chat::domain::service::ChatServiceImpl::new(
chat::outbound::postgres::PgChatRepo::new(pool.clone()),
- Arc::new(ai_toolset::AsyncToolSet::new()),
+ Arc::new(ai_toolset::AsyncToolCollection::new()),
(),
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
entity_access_management::outbound::PgRepository::new(pool.clone()),
@@ -384,6 +384,22 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
ai_stream_registry: crate::service::ai_stream_registry::AiStreamRegistry::new(Arc::new(
redis::Client::open("redis://127.0.0.1:6379/").expect("valid redis url"),
)),
+ mcp_state: {
+ let redis_client =
+ Arc::new(redis::Client::open("redis://127.0.0.1:6379/").expect("valid redis url"));
+ let mcp_key = mcp_client::domain::models::AesKey::try_from(vec![0u8; 32])
+ .expect("valid test key");
+ let mcp_repo =
+ mcp_client::outbound::pg_server_repo::PgServerRepo::new(pool.clone(), mcp_key);
+ let mcp_state_store =
+ mcp_client::outbound::redis_state_store::RedisOAuthStateStore::new(redis_client);
+ let mcp_oauth = mcp_client::domain::service::OAuthService::new(
+ mcp_repo.clone(),
+ mcp_state_store,
+ "http://localhost/mcp/servers/auth/callback".to_string(),
+ );
+ mcp_client::inbound::McpRouterState::new(mcp_repo, mcp_oauth)
+ },
};
Arc::new(api_context)
}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/mod.rs
index ed64b76f9c..c6a7e09cda 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/mod.rs
@@ -72,6 +72,8 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {
fn api_router(api_context: ApiContext) -> Router {
let memory_service = api_context.memory_service.clone();
+ let mcp_state = api_context.mcp_state.clone();
+
let internal_router = Router::new()
.nest("/chats", chats::router(api_context.clone()))
.nest("/stream", stream::router(api_context.clone()))
@@ -80,6 +82,7 @@ fn api_router(api_context: ApiContext) -> Router {
.nest("/preview", preview::router())
.nest("/id_mapping", id_mapping::router())
.merge(memory::inbound::axum_router::memory_router(memory_service))
+ .merge(mcp_client::inbound::mcp_router(mcp_state.clone()))
.with_state(api_context.clone())
.route(
"/chat/completions",
@@ -102,4 +105,5 @@ fn api_router(api_context: ApiContext) -> Router {
Router::new()
.nest("/{version}", internal_router.clone())
.merge(internal_router)
+ .merge(mcp_client::inbound::mcp_oauth_callback_router(mcp_state))
}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
index cd9803602e..c8f6a1d16d 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
@@ -27,6 +27,7 @@ use futures::StreamExt;
use macro_auth::headers::AccessTokenExtractor;
use macro_db_client::dcs::create_chat;
use macro_user_id::user_id::MacroUserIdStr;
+use mcp_client::domain::ports::McpServerStore;
use memory::domain::MemoryService;
use model::user::UserContext;
use model_entity::{Entity, EntityType};
@@ -444,7 +445,8 @@ fn stream_and_save_message(
) {
tracing::trace!(request=?request, "streaming chat request");
let tool_context = ctx.tool_service_context.clone();
- let toolset = ctx.all_tools.clone();
+ let static_tools = ctx.all_tools.clone();
+ let mcp_store = ctx.mcp_state.store();
let request_context = RequestContext {
user_id: user_id.clone(),
@@ -474,6 +476,10 @@ fn stream_and_save_message(
yield json;
}
+ let mcp_records = mcp_store.list(&user_id).await.unwrap_or_default();
+ let toolset = Arc::new(
+ mcp_client::domain::service::CombinedToolSet::new(static_tools, &mcp_records).await,
+ );
let client = ToolLoop::new(toolset, tool_context);
let mut chat = client.chat();
diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
index 33dcb53a94..88b7584f02 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
@@ -17,6 +17,10 @@ use crate::model::{
},
stream::{ChatStream, SendChatMessagePayload, StreamError, ToolSet},
};
+use mcp_client::inbound::axum_router::{
+ self as mcp_api, AddServerRequest, ServerResponse, StartAuthRequest, StartAuthResponse,
+ UpdateServerRequest,
+};
use memory::inbound::axum_router::{self as memory_api, MemoryErrorBody, MemoryResponse};
use crate::api::preview::get_batch_preview::{GetBatchPreviewRequest, GetBatchPreviewResponse};
@@ -76,7 +80,13 @@ use utoipa::OpenApi;
chat_history_batch_messages::get_chat_history_batch_messages_handler,
chat_message::send_chat_message,
stream_stop::stop_chat_stream,
- memory_api::get_memory_handler
+ memory_api::get_memory_handler,
+ mcp_api::list_servers,
+ mcp_api::add_server,
+ mcp_api::update_server,
+ mcp_api::delete_server,
+ mcp_api::start_auth,
+ mcp_api::auth_callback
),
components(
schemas(
@@ -158,6 +168,14 @@ use utoipa::OpenApi;
MemoryResponse,
MemoryErrorBody,
+ // MCP
+ ServerResponse,
+ AddServerRequest,
+ UpdateServerRequest,
+ StartAuthRequest,
+ StartAuthResponse,
+ model_error_response::ErrorResponse,
+
// Tools
ai::tool::schema::ToolSchema,
ai::tool::schema::ToolSchemas,
diff --git a/rust/cloud-storage/document_cognition_service/src/config.rs b/rust/cloud-storage/document_cognition_service/src/config.rs
index 8136f205e4..a5e6e411d1 100644
--- a/rust/cloud-storage/document_cognition_service/src/config.rs
+++ b/rust/cloud-storage/document_cognition_service/src/config.rs
@@ -53,6 +53,8 @@ pub struct Config {
pub cloudfront_signer_public_key_id: String,
/// CloudFront signer private key (secret name or value)
pub cloudfront_signer_private_key: String,
+ /// MCP credentials encryption key (base64-encoded, secret name or value)
+ pub mcp_credentials_key_secret_name: String,
}
env_var!(
@@ -77,6 +79,7 @@ env_var!(
pub DocumentStorageServiceCloudfrontDistributionUrl,
pub DocumentStorageServiceCloudfrontSignerPublicKeyId,
pub DocumentStorageServiceCloudfrontSignerPrivateKeySecretName,
+ pub McpCredentialsKeySecretName,
}
);
@@ -124,6 +127,7 @@ impl Config {
document_storage_service_cloudfront_distribution_url,
document_storage_service_cloudfront_signer_public_key_id,
document_storage_service_cloudfront_signer_private_key_secret_name,
+ mcp_credentials_key_secret_name,
} = env_vars;
Ok(Config {
@@ -154,6 +158,7 @@ impl Config {
document_storage_service_cloudfront_signer_public_key_id.to_string(),
cloudfront_signer_private_key:
document_storage_service_cloudfront_signer_private_key_secret_name.to_string(),
+ mcp_credentials_key_secret_name: mcp_credentials_key_secret_name.to_string(),
})
}
@@ -184,6 +189,7 @@ impl Config {
cloudfront_distribution_url: Default::default(),
cloudfront_signer_public_key_id: Default::default(),
cloudfront_signer_private_key: Default::default(),
+ mcp_credentials_key_secret_name: Default::default(),
}
}
}
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index a326c31fb5..9c7ea08606 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -351,7 +351,7 @@ async fn main() -> anyhow::Result<()> {
let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(
chat::domain::service::ChatServiceImpl::new(
chat::outbound::postgres::PgChatRepo::new(db.clone()),
- Arc::new(ai_toolset::AsyncToolSet::new()),
+ Arc::new(ai_toolset::AsyncToolCollection::new()),
(),
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
entity_access_management::outbound::PgRepository::new(db.clone()),
@@ -391,6 +391,32 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized memory service");
+ let mcp_credentials_key_b64 = match config.environment {
+ Environment::Local => config.mcp_credentials_key_secret_name.clone(),
+ _ => secretsmanager_client
+ .get_secret_value(&config.mcp_credentials_key_secret_name)
+ .await
+ .context("failed to get MCP credentials key from secrets manager")?
+ .to_string(),
+ };
+ let mcp_encryption_key =
+ mcp_client::domain::models::AesKey::try_from(mcp_credentials_key_b64.as_str())
+ .context("invalid MCP credentials encryption key")?;
+ let mcp_server_repo =
+ mcp_client::outbound::pg_server_repo::PgServerRepo::new(db.clone(), mcp_encryption_key);
+ let mcp_redirect_uri = format!(
+ "{}/mcp/servers/auth/callback",
+ config.document_cognition_service_url
+ );
+ let mcp_oauth_state_store =
+ mcp_client::outbound::redis_state_store::RedisOAuthStateStore::new(redis_client.clone());
+ let mcp_oauth = mcp_client::domain::service::OAuthService::new(
+ mcp_server_repo.clone(),
+ mcp_oauth_state_store,
+ mcp_redirect_uri,
+ );
+ let mcp_state = mcp_client::inbound::McpRouterState::new(mcp_server_repo, mcp_oauth);
+
api::setup_and_serve(ApiContext {
db: db.clone(),
email_service_client_external,
@@ -419,6 +445,7 @@ async fn main() -> anyhow::Result<()> {
ai_stream_registry: service::ai_stream_registry::AiStreamRegistry::new(
redis_client.clone(),
),
+ mcp_state,
})
.await
.context("failed to setup and serve api")?;
diff --git a/rust/cloud-storage/documents/src/inbound/toolset/mod.rs b/rust/cloud-storage/documents/src/inbound/toolset/mod.rs
index 126866af6f..a33dfec3cc 100644
--- a/rust/cloud-storage/documents/src/inbound/toolset/mod.rs
+++ b/rust/cloud-storage/documents/src/inbound/toolset/mod.rs
@@ -19,7 +19,7 @@ use crate::{
markdown_init::LexicalSyncMarkdownInitializer,
},
};
-use ai::tool::AsyncToolSet;
+use ai::tool::AsyncToolCollection;
use entity_access::domain::ports::EntityAccessService;
use lexical_client::LexicalClient;
use std::sync::Arc;
@@ -96,12 +96,12 @@ impl<DSvc: DocumentService + DocumentCreationService, ESvc: EntityAccessService>
}
/// Create a document toolset
-pub fn document_toolset<DSvc, ESvc>() -> AsyncToolSet<DocumentToolContext<DSvc, ESvc>>
+pub fn document_toolset<DSvc, ESvc>() -> AsyncToolCollection<DocumentToolContext<DSvc, ESvc>>
where
DSvc: DocumentService + DocumentCreationService,
ESvc: EntityAccessService,
{
- AsyncToolSet::new()
+ AsyncToolCollection::new()
.add_tool::<ReadMetadata, DocumentToolContext<DSvc, ESvc>>()
.add_tool::<ReadContent, DocumentToolContext<DSvc, ESvc>>()
.add_tool::<CreateDocument, DocumentToolContext<DSvc, ESvc>>()
diff --git a/rust/cloud-storage/email/src/inbound/toolset/mod.rs b/rust/cloud-storage/email/src/inbound/toolset/mod.rs
index 724b44fa6d..debc518d6d 100644
--- a/rust/cloud-storage/email/src/inbound/toolset/mod.rs
+++ b/rust/cloud-storage/email/src/inbound/toolset/mod.rs
@@ -12,7 +12,7 @@ use crate::domain::{
models::Link,
ports::{EmailService, GmailTokenProvider},
};
-use ai::tool::{AsyncToolSet, ToolCallError};
+use ai::tool::{AsyncToolCollection, ToolCallError};
use entity_access::domain::ports::EntityAccessService;
use macro_user_id::user_id::MacroUserIdStr;
use std::sync::Arc;
@@ -90,7 +90,7 @@ impl<T: EmailService, G: GmailTokenProvider, E: EntityAccessService> EmailToolCo
}
/// Create the full email toolset including SendEmail.
-pub fn email_toolset<T, G, E>() -> AsyncToolSet<EmailToolContext<T, G, E>>
+pub fn email_toolset<T, G, E>() -> AsyncToolCollection<EmailToolContext<T, G, E>>
where
T: EmailService,
G: GmailTokenProvider,
@@ -100,13 +100,13 @@ where
}
/// Email toolset for the MCP server — excludes SendEmail.
-pub fn mcp_toolset<T, G, E>() -> AsyncToolSet<EmailToolContext<T, G, E>>
+pub fn mcp_toolset<T, G, E>() -> AsyncToolCollection<EmailToolContext<T, G, E>>
where
T: EmailService,
G: GmailTokenProvider,
E: EntityAccessService,
{
- AsyncToolSet::new()
+ AsyncToolCollection::new()
.add_tool::<UpdateThreadLabels, EmailToolContext<T, G, E>>()
.add_tool::<GetThread, EmailToolContext<T, G, E>>()
}
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260512000001_add_mcp_servers_table.down.sql b/rust/cloud-storage/macro_db_client/migrations/20260512000001_add_mcp_servers_table.down.sql
new file mode 100644
index 0000000000..dc282cdce7
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260512000001_add_mcp_servers_table.down.sql
@@ -0,0 +1,2 @@
+DROP INDEX IF EXISTS idx_mcp_servers_user_id;
+DROP TABLE IF EXISTS mcp_servers;
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260512000001_add_mcp_servers_table.sql b/rust/cloud-storage/macro_db_client/migrations/20260512000001_add_mcp_servers_table.sql
new file mode 100644
index 0000000000..cc84c8aeda
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260512000001_add_mcp_servers_table.sql
@@ -0,0 +1,12 @@
+CREATE TABLE IF NOT EXISTS mcp_servers (
+ user_id TEXT NOT NULL REFERENCES "User" ("id") ON DELETE CASCADE,
+ url TEXT NOT NULL,
+ server_name TEXT NOT NULL,
+ credentials BYTEA,
+ enabled BOOLEAN NOT NULL DEFAULT TRUE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ PRIMARY KEY (user_id, url)
+);
+
+CREATE INDEX idx_mcp_servers_user_id ON mcp_servers (user_id);
diff --git a/rust/cloud-storage/mcp_client/.gitignore b/rust/cloud-storage/mcp_client/.gitignore
new file mode 100644
index 0000000000..ea8c4bf7f3
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/.gitignore
@@ -0,0 +1 @@
+/target
diff --git a/rust/cloud-storage/mcp_client/Cargo.toml b/rust/cloud-storage/mcp_client/Cargo.toml
new file mode 100644
index 0000000000..fb95a6a618
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/Cargo.toml
@@ -0,0 +1,29 @@
+[package]
+name = "mcp_client"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+aes-gcm = "0.10"
+ai = { path = "../ai" }
+ai_toolset = { path = "../ai_toolset" }
+anyhow.workspace = true
+oauth2 = { version = "5.0", default-features = false }
+base64.workspace = true
+async-openai.workspace = true
+axum.workspace = true
+futures.workspace = true
+macro_user_id = { path = "../macro_user_id" }
+model-error-response = { path = "../model-error-response" }
+model_user = { path = "../model_user", features = ["axum"] }
+redis = { workspace = true, features = ["aio", "tokio-comp"] }
+reqwest.workspace = true
+rmcp = { workspace = true, features = ["auth", "client", "transport-streamable-http-client-reqwest"] }
+schemars.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+sqlx.workspace = true
+thiserror.workspace = true
+tracing.workspace = true
+utoipa.workspace = true
diff --git a/rust/cloud-storage/mcp_client/src/domain/mod.rs b/rust/cloud-storage/mcp_client/src/domain/mod.rs
new file mode 100644
index 0000000000..96ce5f58c6
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/domain/mod.rs
@@ -0,0 +1,6 @@
+/// Domain models for MCP server connections and tool execution.
+pub mod models;
+/// Port traits consumed by the domain service.
+pub mod ports;
+/// Service orchestration for MCP connections and tool calls.
+pub mod service;
diff --git a/rust/cloud-storage/mcp_client/src/domain/models/aes_key.rs b/rust/cloud-storage/mcp_client/src/domain/models/aes_key.rs
new file mode 100644
index 0000000000..68191e43ca
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/domain/models/aes_key.rs
@@ -0,0 +1,45 @@
+/// A validated 32-byte AES-256 encryption key.
+#[derive(Clone)]
+pub struct AesKey([u8; 32]);
+
+impl AesKey {
+ /// The raw key bytes.
+ pub fn as_bytes(&self) -> &[u8; 32] {
+ &self.0
+ }
+}
+
+impl TryFrom<Vec<u8>> for AesKey {
+ type Error = AesKeyError;
+
+ fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
+ let bytes: [u8; 32] = bytes
+ .try_into()
+ .map_err(|v: Vec<u8>| AesKeyError::InvalidLength(v.len()))?;
+ Ok(Self(bytes))
+ }
+}
+
+impl TryFrom<&str> for AesKey {
+ type Error = AesKeyError;
+
+ /// Decode a base64-encoded key string into an [`AesKey`].
+ fn try_from(b64: &str) -> Result<Self, Self::Error> {
+ use base64::Engine;
+ let bytes = base64::engine::general_purpose::STANDARD
+ .decode(b64.trim())
+ .map_err(AesKeyError::InvalidBase64)?;
+ bytes.try_into()
+ }
+}
+
+/// Errors when constructing an [`AesKey`].
+#[derive(Debug, thiserror::Error)]
+pub enum AesKeyError {
+ /// Key must be exactly 32 bytes.
+ #[error("AES-256 key must be exactly 32 bytes, got {0}")]
+ InvalidLength(usize),
+ /// Base64 decoding failed.
+ #[error("invalid base64: {0}")]
+ InvalidBase64(base64::DecodeError),
+}
diff --git a/rust/cloud-storage/mcp_client/src/domain/models/consts.rs b/rust/cloud-storage/mcp_client/src/domain/models/consts.rs
new file mode 100644
index 0000000000..43a6e061e5
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/domain/models/consts.rs
@@ -0,0 +1,2 @@
+/// Our MCP client publishes this name to servers on-connect
+pub const MCP_CLIENT_NAME: &str = "Macro";
diff --git a/rust/cloud-storage/mcp_client/src/domain/models/mod.rs b/rust/cloud-storage/mcp_client/src/domain/models/mod.rs
new file mode 100644
index 0000000000..af6db65624
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/domain/models/mod.rs
@@ -0,0 +1,10 @@
+mod aes_key;
+mod consts;
+mod result;
+mod server;
+
+pub use aes_key::{AesKey, AesKeyError};
+pub use macro_user_id::user_id::MacroUserIdStr;
+pub use result::{Error, Result};
+pub use rmcp::transport::auth::StoredCredentials;
+pub use server::{McpServer, McpServerConnectionInfo, McpServerRecord, client_info};
diff --git a/rust/cloud-storage/mcp_client/src/domain/models/result.rs b/rust/cloud-storage/mcp_client/src/domain/models/result.rs
new file mode 100644
index 0000000000..c8e34a0a12
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/domain/models/result.rs
@@ -0,0 +1,30 @@
+use thiserror::Error;
+
+/// Domain errors for the MCP client.
+#[derive(Debug, Error)]
+pub enum Error {
+ /// The server requires authentication but no credentials are stored.
+ #[error("no credentials stored for server: {0}")]
+ NoCredentials(String),
+ /// Stored credentials are invalid or expired.
+ #[error("invalid credentials for server: {0}")]
+ InvalidCredentials(String),
+ /// Failed to connect to the MCP server.
+ #[error("connection failed: {0}")]
+ Connection(String),
+ /// The requested tool was not found on any connected server.
+ #[error("unknown tool: {0}")]
+ UnknownTool(String),
+ /// A tool invocation failed.
+ #[error("tool call failed: {0}")]
+ ToolCall(String),
+ /// A mangled tool name already exists in the tool set.
+ #[error("tool name conflict: {0}")]
+ ToolConflict(String),
+ /// An internal or infrastructure error.
+ #[error(transparent)]
+ Internal(#[from] anyhow::Error),
+}
+
+/// Domain result type.
+pub type Result<T> = std::result::Result<T, Error>;
diff --git a/rust/cloud-storage/mcp_client/src/domain/models/server.rs b/rust/cloud-storage/mcp_client/src/domain/models/server.rs
new file mode 100644
index 0000000000..7fc0a9ea2e
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/domain/models/server.rs
@@ -0,0 +1,75 @@
+use super::consts::MCP_CLIENT_NAME;
+use crate::domain::ports::McpConnector;
+use macro_user_id::user_id::MacroUserIdStr;
+use rmcp::RoleClient;
+use rmcp::model::{ClientInfo, Implementation};
+use rmcp::service::{RunningService, ServiceExt};
+use rmcp::transport::StreamableHttpClientTransport;
+use rmcp::transport::auth::{
+ AuthClient, AuthorizationManager, CredentialStore as _, InMemoryCredentialStore,
+ StoredCredentials,
+};
+use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
+use serde::{Deserialize, Serialize};
+
+/// A connected MCP server session.
+pub type McpServer = RunningService<RoleClient, ClientInfo>;
+
+/// Build the client info sent to MCP servers during initialization.
+pub fn client_info() -> ClientInfo {
+ ClientInfo::new(
+ Default::default(),
+ Implementation::new(MCP_CLIENT_NAME, env!("CARGO_PKG_VERSION")),
+ )
+}
+
+/// Connection details for an MCP server.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct McpServerConnectionInfo {
+ /// Human-readable server name.
+ pub name: String,
+ /// The server's streamable HTTP URL.
+ pub url: String,
+}
+
+/// A persisted MCP server entry with connection info and credentials.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct McpServerRecord {
+ /// The user who owns these credentials.
+ pub user_id: MacroUserIdStr<'static>,
+ /// The server URL these credentials authenticate against.
+ pub url: String,
+ /// Name of the MCP server.
+ pub server_name: String,
+ /// The OAuth credentials.
+ #[serde(skip)]
+ pub credentials: Option<StoredCredentials>,
+ /// Whether the user has this toolset enabled.
+ pub enabled: bool,
+}
+
+impl McpConnector for McpServerRecord {
+ async fn connect(&self) -> anyhow::Result<McpServer> {
+ match &self.credentials {
+ Some(credentials) => {
+ let mut auth_manager = AuthorizationManager::new(&self.url).await?;
+ let store = InMemoryCredentialStore::new();
+ store.save(credentials.clone()).await?;
+ auth_manager.set_credential_store(store);
+ auth_manager.initialize_from_store().await?;
+
+ let auth_client = AuthClient::new(reqwest::Client::new(), auth_manager);
+ let config = StreamableHttpClientTransportConfig::with_uri(&*self.url);
+ let transport = StreamableHttpClientTransport::with_client(auth_client, config);
+
+ Ok(client_info().serve(transport).await?)
+ }
+ None => {
+ let transport = StreamableHttpClientTransport::from_uri(&*self.url);
+ Ok(client_info().serve(transport).await?)
+ }
+ }
+ }
+}
diff --git a/rust/cloud-storage/mcp_client/src/domain/ports.rs b/rust/cloud-storage/mcp_client/src/domain/ports.rs
new file mode 100644
index 0000000000..6b9001bdd1
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/domain/ports.rs
@@ -0,0 +1,101 @@
+use super::models::{MacroUserIdStr, McpServer, McpServerRecord, StoredCredentials};
+
+/// Port for persisting MCP server records, keyed by user.
+pub trait McpServerStore: Send + Sync + 'static {
+ /// Error type for store operations.
+ type Err: Send + std::fmt::Debug;
+
+ /// Persist a server record, overwriting any existing entry for the same user and URL.
+ fn save(&self, record: &McpServerRecord) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Load a server record for a user and server URL. Returns `None` if not stored.
+ fn load(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ server_url: &str,
+ ) -> impl Future<Output = Result<Option<McpServerRecord>, Self::Err>> + Send;
+
+ /// Delete a server record for a user and server URL.
+ fn delete(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ server_url: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// List all stored server records for a user.
+ fn list(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<McpServerRecord>, Self::Err>> + Send;
+}
+
+/// Port for establishing a connection to an MCP server.
+pub trait McpConnector: Send + Sync {
+ /// Connect to the MCP server described by this value.
+ fn connect(&self) -> impl Future<Output = anyhow::Result<McpServer>> + Send;
+}
+
+/// Everything needed to resume the OAuth flow on callback.
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
+pub struct PendingAuth {
+ /// PKCE verifier generated during authorization start.
+ pub pkce_verifier: String,
+ /// OAuth client ID obtained during dynamic registration.
+ pub client_id: String,
+ /// OAuth client secret, if the server issued one.
+ pub client_secret: Option<String>,
+ /// The user who initiated the flow.
+ pub user_id: String,
+ /// The MCP server URL being authorized.
+ pub server_url: String,
+ /// Human-readable server name.
+ pub server_name: String,
+}
+
+/// Port for storing ephemeral OAuth state across requests.
+///
+/// Implementations must support cross-instance access (e.g. Redis) and
+/// should expire entries after a reasonable TTL.
+pub trait OAuthStateStore: Send + Sync + 'static {
+ /// Save a pending authorization, keyed by CSRF state token.
+ fn save(
+ &self,
+ csrf_token: &str,
+ pending: PendingAuth,
+ ) -> impl Future<Output = anyhow::Result<()>> + Send;
+
+ /// Load and remove a pending authorization by CSRF state token.
+ fn take(
+ &self,
+ csrf_token: &str,
+ ) -> impl Future<Output = anyhow::Result<Option<PendingAuth>>> + Send;
+}
+
+/// Port for driving the OAuth authorization-code flow for an MCP server.
+///
+/// Implementations manage the full PKCE handshake: discovering server metadata,
+/// registering a client, building the authorization URL, and exchanging the
+/// callback code for tokens.
+pub trait OAuthClient: Send + Sync + 'static {
+ /// Begin the OAuth flow for `server_url`.
+ ///
+ /// Discovers the server's OAuth metadata, registers a dynamic client if
+ /// needed, and returns the authorization URL the user should be redirected to.
+ fn start_authorization(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ server_url: &str,
+ server_name: &str,
+ ) -> impl Future<Output = anyhow::Result<String>> + Send;
+
+ /// Complete the OAuth flow using the `code` and `state` returned by the
+ /// authorization server's redirect.
+ ///
+ /// Exchanges the authorization code for tokens and returns the resulting
+ /// credentials ready to be persisted.
+ fn exchange_authorization_code(
+ &self,
+ code: &str,
+ state: &str,
+ ) -> impl Future<Output = anyhow::Result<StoredCredentials>> + Send;
+}
diff --git a/rust/cloud-storage/mcp_client/src/domain/service/mod.rs b/rust/cloud-storage/mcp_client/src/domain/service/mod.rs
new file mode 100644
index 0000000000..6dacdebbda
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/domain/service/mod.rs
@@ -0,0 +1,6 @@
+mod oauth;
+/// MCP tool set and combined tool set for the AI loop.
+pub mod toolset;
+
+pub use oauth::OAuthService;
+pub use toolset::{CombinedToolSet, McpToolSet};
diff --git a/rust/cloud-storage/mcp_client/src/domain/service/oauth.rs b/rust/cloud-storage/mcp_client/src/domain/service/oauth.rs
new file mode 100644
index 0000000000..ae98a3fc13
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/domain/service/oauth.rs
@@ -0,0 +1,150 @@
+use crate::domain::models::{MacroUserIdStr, McpServerRecord, StoredCredentials};
+use crate::domain::ports::{McpServerStore, OAuthClient, OAuthStateStore, PendingAuth};
+use macro_user_id::cowlike::CowLike;
+use rmcp::transport::auth::{
+ AuthorizationManager, CredentialStore as _, InMemoryCredentialStore, InMemoryStateStore,
+ OAuthClientConfig, StateStore as _, StoredAuthorizationState,
+};
+
+/// Drives the OAuth authorization-code flow, storing ephemeral state in an
+/// [`OAuthStateStore`] and persisting credentials to a [`McpServerStore`].
+pub struct OAuthService<S, R> {
+ server_store: S,
+ state_store: R,
+ redirect_uri: String,
+}
+
+impl<S, R> OAuthService<S, R> {
+ /// Create a new OAuth service.
+ ///
+ /// `redirect_uri` is the callback URL registered with OAuth providers
+ /// (e.g. `https://api.example.com/mcp/auth/callback`).
+ pub fn new(server_store: S, state_store: R, redirect_uri: String) -> Self {
+ Self {
+ server_store,
+ state_store,
+ redirect_uri,
+ }
+ }
+}
+
+impl<S, R> OAuthClient for OAuthService<S, R>
+where
+ S: McpServerStore,
+ R: OAuthStateStore,
+ anyhow::Error: From<S::Err>,
+{
+ async fn start_authorization(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ server_url: &str,
+ server_name: &str,
+ ) -> anyhow::Result<String> {
+ let mut auth_manager = AuthorizationManager::new(server_url).await?;
+ let metadata = auth_manager.discover_metadata().await?;
+ auth_manager.set_metadata(metadata);
+
+ let in_memory_state = InMemoryStateStore::new();
+ auth_manager.set_state_store(in_memory_state.clone());
+ auth_manager.set_credential_store(InMemoryCredentialStore::new());
+
+ let client_config = auth_manager
+ .register_client("macro", &self.redirect_uri, &[])
+ .await?;
+
+ let auth_url = auth_manager.get_authorization_url(&[]).await?;
+ let csrf_token = extract_state_param(&auth_url)?;
+
+ let pkce_state = in_memory_state
+ .load(&csrf_token)
+ .await?
+ .ok_or_else(|| anyhow::anyhow!("PKCE state not found after generating auth URL"))?;
+
+ let pending = PendingAuth {
+ pkce_verifier: pkce_state.pkce_verifier,
+ client_id: client_config.client_id,
+ client_secret: client_config.client_secret,
+ user_id: user_id.as_ref().to_string(),
+ server_url: server_url.to_string(),
+ server_name: server_name.to_string(),
+ };
+ self.state_store.save(&csrf_token, pending).await?;
+
+ tracing::info!(csrf_token, redirect_uri = %self.redirect_uri, "stored pending OAuth state");
+ Ok(auth_url)
+ }
+
+ async fn exchange_authorization_code(
+ &self,
+ code: &str,
+ state: &str,
+ ) -> anyhow::Result<StoredCredentials> {
+ let pending = self
+ .state_store
+ .take(state)
+ .await?
+ .ok_or_else(|| anyhow::anyhow!("no pending authorization for state"))?;
+
+ let mut auth_manager = AuthorizationManager::new(&pending.server_url).await?;
+ let metadata = auth_manager.discover_metadata().await?;
+ auth_manager.set_metadata(metadata);
+
+ let pkce_state = StoredAuthorizationState::new(
+ &oauth2::PkceCodeVerifier::new(pending.pkce_verifier),
+ &oauth2::CsrfToken::new(state.to_string()),
+ );
+ let in_memory_state = InMemoryStateStore::new();
+ in_memory_state.save(state, pkce_state).await?;
+ auth_manager.set_state_store(in_memory_state);
+
+ let credential_store = InMemoryCredentialStore::new();
+ auth_manager.set_credential_store(credential_store.clone());
+
+ let mut client_config =
+ OAuthClientConfig::new(pending.client_id, self.redirect_uri.clone());
+ if let Some(secret) = pending.client_secret {
+ client_config = client_config.with_client_secret(secret);
+ }
+ auth_manager.configure_client(client_config)?;
+
+ auth_manager
+ .exchange_code_for_token(code, state)
+ .await
+ .inspect_err(|e| tracing::error!(error = ?e, "exchange_code_for_token failed"))?;
+
+ let credentials = credential_store
+ .load()
+ .await
+ .inspect_err(|e| tracing::error!(error = ?e, "credential store load failed"))?
+ .ok_or_else(|| anyhow::anyhow!("credentials missing after token exchange"))?;
+
+ let user_id = MacroUserIdStr::parse_from_str(&pending.user_id)
+ .map_err(|e| anyhow::anyhow!("invalid user_id in pending context: {e}"))?
+ .into_owned();
+
+ let record = McpServerRecord {
+ user_id,
+ url: pending.server_url,
+ server_name: pending.server_name,
+ credentials: Some(credentials.clone()),
+ enabled: true,
+ };
+
+ self.server_store
+ .save(&record)
+ .await
+ .inspect_err(|e| tracing::error!(error = ?e, "server store save failed"))
+ .map_err(anyhow::Error::from)?;
+
+ tracing::info!("OAuth flow completed successfully");
+ Ok(credentials)
+ }
+}
+
+fn extract_state_param(url: &str) -> anyhow::Result<String> {
+ reqwest::Url::parse(url)?
+ .query_pairs()
+ .find(|(k, _)| k == "state")
+ .map(|(_, v)| v.into_owned())
+ .ok_or_else(|| anyhow::anyhow!("missing state parameter in authorization URL"))
+}
diff --git a/rust/cloud-storage/mcp_client/src/domain/service/toolset.rs b/rust/cloud-storage/mcp_client/src/domain/service/toolset.rs
new file mode 100644
index 0000000000..572f1213da
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/domain/service/toolset.rs
@@ -0,0 +1,284 @@
+use crate::domain::models::{Error, McpServerRecord};
+use crate::domain::ports::McpConnector;
+use ai::openai_toolset::OpenAIToolSetExt;
+use ai_toolset::{
+ AsyncToolCollection, RequestContext, RequestSchema, ToolInfo, ToolResult, ToolSet, ToolSetError,
+};
+use async_openai::types::chat::{ChatCompletionTool, ChatCompletionTools, FunctionObject};
+use rmcp::RoleClient;
+use rmcp::model::{CallToolRequestParams, CallToolResult, Tool};
+use rmcp::service::Peer;
+use schemars::Schema;
+use std::collections::BTreeMap;
+use std::pin::Pin;
+use std::sync::Arc;
+
+const MANGLED_PREFIX: &str = "mcp_";
+
+/// A mangled tool name in the format `mcp_<server>_<tool>`.
+#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+struct MangledName(String);
+
+impl MangledName {
+ fn new(server_name: &str, tool_name: &str) -> Self {
+ Self(format!("{MANGLED_PREFIX}{server_name}_{tool_name}"))
+ }
+
+ fn parse(s: &str) -> Option<(&str, &str)> {
+ s.strip_prefix(MANGLED_PREFIX)?.split_once('_')
+ }
+
+ fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl std::fmt::Display for MangledName {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+struct RegisteredTool {
+ peer: Peer<RoleClient>,
+ tool: Tool,
+}
+
+/// Dispatches tool calls to connected MCP servers using name-mangled routing.
+///
+/// Every tool is exposed as `mcp_<server_name>_<tool_name>` to guarantee
+/// uniqueness across servers.
+pub struct McpToolSet {
+ tools: BTreeMap<MangledName, RegisteredTool>,
+}
+
+impl McpToolSet {
+ /// Connect to every server in `records` concurrently, discover tools, and
+ /// register them.
+ ///
+ /// Servers that fail to connect or list tools are silently skipped.
+ #[tracing::instrument(skip_all)]
+ pub async fn new(records: &[McpServerRecord]) -> Self {
+ let futs = records
+ .iter()
+ .filter(|r| r.enabled)
+ .map(|record| async move {
+ let client = record.connect().await.inspect_err(|e| {
+ tracing::warn!(server = %record.server_name, error = ?e, "failed to connect");
+ }).ok()?;
+
+ let server_tools = match client.list_all_tools().await {
+ Ok(t) => t,
+ Err(e) => {
+ tracing::warn!(server = %record.server_name, error = ?e, "failed to list tools");
+ let _ = client.cancel().await;
+ return None;
+ }
+ };
+
+ Some((record.server_name.clone(), client, server_tools))
+ });
+
+ let results = futures::future::join_all(futs).await;
+
+ let mut tools = BTreeMap::new();
+ for (server_name, client, server_tools) in results.into_iter().flatten() {
+ for tool in server_tools {
+ let mangled = MangledName::new(&server_name, &tool.name);
+
+ if tools.contains_key(&mangled) {
+ tracing::warn!(%mangled, "skipping duplicate tool");
+ continue;
+ }
+
+ tools.insert(
+ mangled,
+ RegisteredTool {
+ peer: client.clone(),
+ tool,
+ },
+ );
+ }
+ }
+
+ Self { tools }
+ }
+
+ /// Returns `true` when no tools were discovered.
+ pub fn is_empty(&self) -> bool {
+ self.tools.is_empty()
+ }
+
+ async fn call_tool(
+ &self,
+ name: &str,
+ arguments: serde_json::Map<String, serde_json::Value>,
+ ) -> Result<CallToolResult, Error> {
+ let key = MangledName(name.to_owned());
+ let entry = self
+ .tools
+ .get(&key)
+ .ok_or_else(|| Error::UnknownTool(name.to_owned()))?;
+
+ let params = CallToolRequestParams::new(entry.tool.name.clone()).with_arguments(arguments);
+
+ entry
+ .peer
+ .call_tool(params)
+ .await
+ .map_err(|e| Error::ToolCall(e.to_string()))
+ }
+}
+
+impl<Context: Send + Sync + 'static> ToolSet<Context> for McpToolSet {
+ fn try_tool_call<'a>(
+ &'a self,
+ _context: Context,
+ _request_context: RequestContext,
+ tool_name: &'a str,
+ json: &'a serde_json::Value,
+ ) -> Pin<
+ Box<dyn Future<Output = Result<ToolResult<serde_json::Value>, ToolSetError>> + 'a + Send>,
+ > {
+ Box::pin(async move {
+ let arguments = match json {
+ serde_json::Value::Object(map) => map.clone(),
+ _ => serde_json::Map::new(),
+ };
+
+ let result = self
+ .call_tool(tool_name, arguments)
+ .await
+ .map_err(|e| ToolSetError::NotFound(e.to_string()))?;
+
+ let text = result
+ .content
+ .into_iter()
+ .filter_map(|c| c.raw.as_text().map(|t| t.text.clone()))
+ .collect::<Vec<_>>()
+ .join("");
+
+ let value = serde_json::Value::String(text);
+
+ if result.is_error.unwrap_or(false) {
+ Err(ToolSetError::NotFound(value.to_string()))
+ } else {
+ Ok(Ok(value))
+ }
+ })
+ }
+
+ fn request_schemas(&self) -> Option<Vec<RequestSchema>> {
+ let schemas: Vec<_> = self
+ .tools
+ .iter()
+ .map(|(mangled, entry)| RequestSchema {
+ name: mangled.as_str().to_string(),
+ schema: Schema::from((*entry.tool.input_schema).clone()),
+ })
+ .collect();
+
+ if schemas.is_empty() {
+ None
+ } else {
+ Some(schemas)
+ }
+ }
+
+ fn routing_description<'a>(&'a self, tool_name: &'a str) -> Option<ToolInfo> {
+ let (server_name, original_name) = MangledName::parse(tool_name)?;
+ Some(ToolInfo::ExternalTool {
+ service_name: server_name.to_owned(),
+ tool_name: original_name.to_owned(),
+ })
+ }
+}
+
+impl OpenAIToolSetExt for McpToolSet {
+ fn openai_chatcompletion_toolset(&self) -> Vec<ChatCompletionTools> {
+ self.tools
+ .iter()
+ .map(|(mangled, entry)| {
+ ChatCompletionTools::Function(ChatCompletionTool {
+ function: FunctionObject {
+ name: mangled.as_str().to_string(),
+ description: entry.tool.description.as_ref().map(|d| d.to_string()),
+ parameters: Some(
+ serde_json::to_value(&*entry.tool.input_schema).unwrap_or_default(),
+ ),
+ strict: Some(false),
+ },
+ })
+ })
+ .collect()
+ }
+}
+
+/// Wraps a static [`AsyncToolCollection`] and an optional [`McpToolSet`],
+/// presenting them as a single toolset to the AI loop.
+pub struct CombinedToolSet<T> {
+ static_tools: Arc<AsyncToolCollection<T>>,
+ mcp_tools: McpToolSet,
+}
+
+impl<T> CombinedToolSet<T> {
+ /// Build a combined toolset from the static tools and the user's MCP servers.
+ pub async fn new(
+ static_tools: Arc<AsyncToolCollection<T>>,
+ records: &[McpServerRecord],
+ ) -> Self {
+ let mcp_tools = McpToolSet::new(records).await;
+ Self {
+ static_tools,
+ mcp_tools,
+ }
+ }
+}
+
+impl<T: Send + Sync + 'static> ToolSet<T> for CombinedToolSet<T> {
+ fn try_tool_call<'a>(
+ &'a self,
+ context: T,
+ request_context: RequestContext,
+ tool_name: &'a str,
+ json: &'a serde_json::Value,
+ ) -> Pin<
+ Box<dyn Future<Output = Result<ToolResult<serde_json::Value>, ToolSetError>> + 'a + Send>,
+ > {
+ if tool_name.starts_with(MANGLED_PREFIX) {
+ self.mcp_tools
+ .try_tool_call(context, request_context, tool_name, json)
+ } else {
+ self.static_tools
+ .try_tool_call(context, request_context, tool_name, json)
+ }
+ }
+
+ fn request_schemas(&self) -> Option<Vec<RequestSchema>> {
+ let mut schemas = self.static_tools.request_schemas().unwrap_or_default();
+ schemas.extend(
+ <McpToolSet as ToolSet<T>>::request_schemas(&self.mcp_tools).unwrap_or_default(),
+ );
+ if schemas.is_empty() {
+ None
+ } else {
+ Some(schemas)
+ }
+ }
+
+ fn routing_description<'a>(&'a self, tool_name: &'a str) -> Option<ToolInfo> {
+ if tool_name.starts_with(MANGLED_PREFIX) {
+ <McpToolSet as ToolSet<T>>::routing_description(&self.mcp_tools, tool_name)
+ } else {
+ self.static_tools.routing_description(tool_name)
+ }
+ }
+}
+
+impl<T: Send + Sync + 'static> OpenAIToolSetExt for CombinedToolSet<T> {
+ fn openai_chatcompletion_toolset(&self) -> Vec<ChatCompletionTools> {
+ let mut tools = self.static_tools.openai_chatcompletion_toolset();
+ tools.extend(self.mcp_tools.openai_chatcompletion_toolset());
+ tools
+ }
+}
diff --git a/rust/cloud-storage/mcp_client/src/inbound/axum_router.rs b/rust/cloud-storage/mcp_client/src/inbound/axum_router.rs
new file mode 100644
index 0000000000..c5817f9f1e
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/inbound/axum_router.rs
@@ -0,0 +1,405 @@
+use crate::domain::{
+ models::McpServerRecord,
+ ports::{McpServerStore, OAuthClient},
+};
+use axum::{
+ Json, Router,
+ extract::{Query, State},
+ http::StatusCode,
+ response::IntoResponse,
+ routing::{delete, get, post, put},
+};
+use model_error_response::ErrorResponse;
+use model_user::axum_extractor::MacroUserExtractor;
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+use utoipa::{IntoParams, ToSchema};
+
+/// Shared state for the MCP router.
+pub struct McpRouterState<S, O> {
+ store: Arc<S>,
+ oauth: Arc<O>,
+}
+
+impl<S, O> Clone for McpRouterState<S, O> {
+ fn clone(&self) -> Self {
+ Self {
+ store: self.store.clone(),
+ oauth: self.oauth.clone(),
+ }
+ }
+}
+
+impl<S, O> McpRouterState<S, O>
+where
+ S: McpServerStore,
+ O: OAuthClient,
+{
+ /// Create a new router state from a server store and OAuth client.
+ pub fn new(store: S, oauth: O) -> Self {
+ Self {
+ store: Arc::new(store),
+ oauth: Arc::new(oauth),
+ }
+ }
+
+ /// Access the underlying server store.
+ pub fn store(&self) -> Arc<S> {
+ self.store.clone()
+ }
+}
+
+/// Authenticated MCP routes (CRUD + start auth).
+pub fn mcp_router<S, O, Global>(state: McpRouterState<S, O>) -> Router<Global>
+where
+ S: McpServerStore,
+ O: OAuthClient,
+ anyhow::Error: From<S::Err>,
+ Global: Send + Sync,
+{
+ Router::new()
+ .route("/mcp/servers", get(list_servers::<S, O>))
+ .route("/mcp/servers", post(add_server::<S, O>))
+ .route("/mcp/servers", put(update_server::<S, O>))
+ .route("/mcp/servers", delete(delete_server::<S, O>))
+ .route("/mcp/servers/auth/start", post(start_auth::<S, O>))
+ .with_state(state)
+}
+
+/// Unauthenticated OAuth callback route.
+pub fn mcp_oauth_callback_router<S, O, Global>(state: McpRouterState<S, O>) -> Router<Global>
+where
+ S: McpServerStore,
+ O: OAuthClient,
+ anyhow::Error: From<S::Err>,
+ Global: Send + Sync,
+{
+ Router::new()
+ .route("/mcp/servers/auth/callback", get(auth_callback::<S, O>))
+ .with_state(state)
+}
+
+// -- request / response types ------------------------------------------------
+
+/// Request body for adding a new MCP server.
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct AddServerRequest {
+ /// The MCP server's streamable HTTP URL.
+ url: String,
+ /// Human-readable name for the server.
+ server_name: String,
+}
+
+/// Request body for updating an MCP server.
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct UpdateServerRequest {
+ /// The server URL to update.
+ url: String,
+ /// New name for the server.
+ #[serde(default)]
+ server_name: Option<String>,
+ /// Enable or disable the server.
+ #[serde(default)]
+ enabled: Option<bool>,
+}
+
+/// Query parameters for deleting an MCP server.
+#[derive(Debug, Deserialize, IntoParams)]
+#[into_params(parameter_in = Query)]
+pub struct DeleteServerParams {
+ /// The server URL to delete.
+ url: String,
+}
+
+/// Request body for starting an OAuth authorization flow.
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct StartAuthRequest {
+ /// The MCP server URL to authorize against.
+ server_url: String,
+ /// Human-readable name for the server.
+ server_name: String,
+}
+
+/// Response from starting an OAuth authorization flow.
+#[derive(Debug, Serialize, ToSchema)]
+pub struct StartAuthResponse {
+ /// The OAuth authorization URL to redirect the user to.
+ authorization_url: String,
+}
+
+/// Query parameters received on the OAuth callback redirect.
+#[derive(Debug, Deserialize, IntoParams)]
+#[into_params(parameter_in = Query)]
+pub struct AuthCallbackParams {
+ /// Authorization code from the OAuth provider.
+ code: String,
+ /// CSRF state parameter.
+ state: String,
+}
+
+/// An MCP server record as returned by the API.
+#[derive(Debug, Serialize, ToSchema)]
+pub struct ServerResponse {
+ /// The MCP server URL.
+ url: String,
+ /// Human-readable server name.
+ server_name: String,
+ /// Whether the server is enabled for tool use.
+ enabled: bool,
+ /// Whether the server has valid stored credentials.
+ authenticated: bool,
+}
+
+impl ServerResponse {
+ fn from_record(record: &McpServerRecord) -> Self {
+ Self {
+ url: record.url.clone(),
+ server_name: record.server_name.clone(),
+ enabled: record.enabled,
+ authenticated: record.credentials.is_some(),
+ }
+ }
+}
+
+// -- error --------------------------------------------------------------------
+
+/// Error type for MCP HTTP handlers.
+#[derive(Debug, thiserror::Error)]
+pub enum McpHandlerErr {
+ /// The requested server was not found.
+ #[error("server not found")]
+ NotFound,
+ /// An internal error occurred.
+ #[error("{0}")]
+ Internal(#[from] anyhow::Error),
+}
+
+impl IntoResponse for McpHandlerErr {
+ fn into_response(self) -> axum::response::Response {
+ let status = match &self {
+ McpHandlerErr::NotFound => StatusCode::NOT_FOUND,
+ McpHandlerErr::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+ (
+ status,
+ Json(ErrorResponse {
+ message: self.to_string().into(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+// -- handlers -----------------------------------------------------------------
+
+#[utoipa::path(
+ get,
+ path = "/mcp/servers",
+ tag = "mcp",
+ operation_id = "list_mcp_servers",
+ responses(
+ (status = 200, body = Vec<ServerResponse>),
+ (status = 401, body = String),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+/// List all MCP servers configured for the authenticated user.
+pub async fn list_servers<S, O>(
+ State(state): State<McpRouterState<S, O>>,
+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+) -> Result<Json<Vec<ServerResponse>>, McpHandlerErr>
+where
+ S: McpServerStore,
+ O: OAuthClient,
+ anyhow::Error: From<S::Err>,
+{
+ let records = state
+ .store
+ .list(&macro_user_id)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ Ok(Json(
+ records.iter().map(ServerResponse::from_record).collect(),
+ ))
+}
+
+#[utoipa::path(
+ post,
+ path = "/mcp/servers",
+ tag = "mcp",
+ operation_id = "add_mcp_server",
+ request_body = AddServerRequest,
+ responses(
+ (status = 201, body = ServerResponse),
+ (status = 401, body = String),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+/// Add a new MCP server for the authenticated user.
+pub async fn add_server<S, O>(
+ State(state): State<McpRouterState<S, O>>,
+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+ Json(body): Json<AddServerRequest>,
+) -> Result<(StatusCode, Json<ServerResponse>), McpHandlerErr>
+where
+ S: McpServerStore,
+ O: OAuthClient,
+ anyhow::Error: From<S::Err>,
+{
+ let record = McpServerRecord {
+ user_id: macro_user_id,
+ url: body.url,
+ server_name: body.server_name,
+ credentials: None,
+ enabled: true,
+ };
+
+ state
+ .store
+ .save(&record)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ Ok((
+ StatusCode::CREATED,
+ Json(ServerResponse::from_record(&record)),
+ ))
+}
+
+#[utoipa::path(
+ put,
+ path = "/mcp/servers",
+ tag = "mcp",
+ operation_id = "update_mcp_server",
+ request_body = UpdateServerRequest,
+ responses(
+ (status = 200, body = ServerResponse),
+ (status = 401, body = String),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+/// Update an existing MCP server's name or enabled status.
+pub async fn update_server<S, O>(
+ State(state): State<McpRouterState<S, O>>,
+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+ Json(body): Json<UpdateServerRequest>,
+) -> Result<Json<ServerResponse>, McpHandlerErr>
+where
+ S: McpServerStore,
+ O: OAuthClient,
+ anyhow::Error: From<S::Err>,
+{
+ let mut record = state
+ .store
+ .load(&macro_user_id, &body.url)
+ .await
+ .map_err(anyhow::Error::from)?
+ .ok_or(McpHandlerErr::NotFound)?;
+
+ if let Some(name) = body.server_name {
+ record.server_name = name;
+ }
+ if let Some(enabled) = body.enabled {
+ record.enabled = enabled;
+ }
+
+ state
+ .store
+ .save(&record)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ Ok(Json(ServerResponse::from_record(&record)))
+}
+
+#[utoipa::path(
+ delete,
+ path = "/mcp/servers",
+ tag = "mcp",
+ operation_id = "delete_mcp_server",
+ params(DeleteServerParams),
+ responses(
+ (status = 204),
+ (status = 401, body = String),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+/// Delete an MCP server by URL.
+pub async fn delete_server<S, O>(
+ State(state): State<McpRouterState<S, O>>,
+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+ Query(params): Query<DeleteServerParams>,
+) -> Result<StatusCode, McpHandlerErr>
+where
+ S: McpServerStore,
+ O: OAuthClient,
+ anyhow::Error: From<S::Err>,
+{
+ state
+ .store
+ .delete(&macro_user_id, &params.url)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ Ok(StatusCode::NO_CONTENT)
+}
+
+#[utoipa::path(
+ post,
+ path = "/mcp/servers/auth/start",
+ tag = "mcp",
+ operation_id = "start_mcp_auth",
+ request_body = StartAuthRequest,
+ responses(
+ (status = 200, body = StartAuthResponse),
+ (status = 401, body = String),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+/// Start the OAuth authorization flow for an MCP server.
+pub async fn start_auth<S, O>(
+ State(state): State<McpRouterState<S, O>>,
+ MacroUserExtractor { macro_user_id, .. }: MacroUserExtractor,
+ Json(body): Json<StartAuthRequest>,
+) -> Result<Json<StartAuthResponse>, McpHandlerErr>
+where
+ S: McpServerStore,
+ O: OAuthClient,
+{
+ let authorization_url = state
+ .oauth
+ .start_authorization(&macro_user_id, &body.server_url, &body.server_name)
+ .await?;
+
+ Ok(Json(StartAuthResponse { authorization_url }))
+}
+
+#[utoipa::path(
+ get,
+ path = "/mcp/servers/auth/callback",
+ tag = "mcp",
+ operation_id = "mcp_auth_callback",
+ params(AuthCallbackParams),
+ responses(
+ (status = 200, description = "OAuth flow completed successfully"),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+/// OAuth callback endpoint — receives code and state from the authorization server.
+pub async fn auth_callback<S, O>(
+ State(state): State<McpRouterState<S, O>>,
+ Query(params): Query<AuthCallbackParams>,
+) -> Result<StatusCode, McpHandlerErr>
+where
+ S: McpServerStore,
+ O: OAuthClient,
+{
+ state
+ .oauth
+ .exchange_authorization_code(&params.code, &params.state)
+ .await?;
+
+ Ok(StatusCode::OK)
+}
diff --git a/rust/cloud-storage/mcp_client/src/inbound/mod.rs b/rust/cloud-storage/mcp_client/src/inbound/mod.rs
new file mode 100644
index 0000000000..d081a2eda7
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/inbound/mod.rs
@@ -0,0 +1,4 @@
+/// Axum HTTP adapter for MCP server management and OAuth callbacks.
+pub mod axum_router;
+
+pub use axum_router::{McpRouterState, mcp_oauth_callback_router, mcp_router};
diff --git a/rust/cloud-storage/mcp_client/src/lib.rs b/rust/cloud-storage/mcp_client/src/lib.rs
new file mode 100644
index 0000000000..f57843f4eb
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/lib.rs
@@ -0,0 +1,11 @@
+#![deny(missing_docs)]
+//! MCP client library for web-based MCP server integration.
+
+/// Domain layer: models, ports, and service.
+pub mod domain;
+
+/// Inbound adapters (HTTP/axum).
+pub mod inbound;
+
+/// Outbound adapters (Postgres).
+pub mod outbound;
diff --git a/rust/cloud-storage/mcp_client/src/outbound/mod.rs b/rust/cloud-storage/mcp_client/src/outbound/mod.rs
new file mode 100644
index 0000000000..e061746c9e
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/outbound/mod.rs
@@ -0,0 +1,4 @@
+/// Postgres-backed repository implementing [`McpServerStore`](crate::domain::ports::McpServerStore).
+pub mod pg_server_repo;
+/// Redis-backed store implementing [`OAuthStateStore`](crate::domain::ports::OAuthStateStore).
+pub mod redis_state_store;
diff --git a/rust/cloud-storage/mcp_client/src/outbound/pg_server_repo.rs b/rust/cloud-storage/mcp_client/src/outbound/pg_server_repo.rs
new file mode 100644
index 0000000000..6b142ebee2
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/outbound/pg_server_repo.rs
@@ -0,0 +1,177 @@
+use crate::domain::{
+ models::{AesKey, MacroUserIdStr, McpServerRecord, StoredCredentials},
+ ports::McpServerStore,
+};
+use aes_gcm::{
+ Aes256Gcm, Key, Nonce,
+ aead::{Aead, AeadCore, KeyInit, OsRng},
+};
+use macro_user_id::cowlike::CowLike;
+use sqlx::PgPool;
+
+const NONCE_LEN: usize = 12;
+
+/// Postgres-backed [`McpServerStore`] with AES-256-GCM encryption for credentials.
+#[derive(Clone)]
+pub struct PgServerRepo {
+ pool: PgPool,
+ encryption_key: AesKey,
+}
+
+impl PgServerRepo {
+ /// Wrap an existing connection pool with an AES-256-GCM encryption key.
+ pub fn new(pool: PgPool, encryption_key: AesKey) -> Self {
+ Self {
+ pool,
+ encryption_key,
+ }
+ }
+
+ fn encrypt(&self, creds: &StoredCredentials) -> Result<Vec<u8>, sqlx::Error> {
+ let plaintext =
+ serde_json::to_vec(creds).map_err(|e| sqlx::Error::Protocol(e.to_string()))?;
+ let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(self.encryption_key.as_bytes()));
+ let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
+ let ciphertext = cipher
+ .encrypt(&nonce, plaintext.as_ref())
+ .map_err(|e| sqlx::Error::Protocol(format!("credential encryption failed: {e}")))?;
+ let mut out = Vec::with_capacity(NONCE_LEN + ciphertext.len());
+ out.extend_from_slice(&nonce);
+ out.extend(ciphertext);
+ Ok(out)
+ }
+
+ fn decrypt(&self, data: &[u8]) -> Result<StoredCredentials, sqlx::Error> {
+ if data.len() <= NONCE_LEN {
+ return Err(sqlx::Error::Decode(
+ "credential ciphertext too short".into(),
+ ));
+ }
+ let (nonce_bytes, ciphertext) = data.split_at(NONCE_LEN);
+ let nonce = Nonce::from_slice(nonce_bytes);
+ let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(self.encryption_key.as_bytes()));
+ let plaintext = cipher.decrypt(nonce, ciphertext).map_err(|e| {
+ sqlx::Error::Decode(format!("credential decryption failed: {e}").into())
+ })?;
+ serde_json::from_slice(&plaintext).map_err(|e| sqlx::Error::Decode(Box::new(e)))
+ }
+}
+
+impl McpServerStore for PgServerRepo {
+ type Err = sqlx::Error;
+
+ async fn save(&self, record: &McpServerRecord) -> Result<(), Self::Err> {
+ let encrypted: Option<Vec<u8>> = record
+ .credentials
+ .as_ref()
+ .map(|c| self.encrypt(c))
+ .transpose()?;
+
+ sqlx::query!(
+ r#"
+ INSERT INTO mcp_servers (user_id, url, server_name, credentials, enabled)
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (user_id, url) DO UPDATE
+ SET server_name = EXCLUDED.server_name,
+ credentials = EXCLUDED.credentials,
+ enabled = EXCLUDED.enabled,
+ updated_at = NOW()
+ "#,
+ record.user_id.as_ref(),
+ record.url,
+ record.server_name,
+ encrypted.as_deref(),
+ record.enabled,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+
+ async fn load(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ server_url: &str,
+ ) -> Result<Option<McpServerRecord>, Self::Err> {
+ let row = sqlx::query!(
+ r#"
+ SELECT user_id, url, server_name, credentials, enabled
+ FROM mcp_servers
+ WHERE user_id = $1 AND url = $2
+ "#,
+ user_id.as_ref(),
+ server_url,
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+
+ row.map(|r| self.to_record(r.user_id, r.url, r.server_name, r.credentials, r.enabled))
+ .transpose()
+ }
+
+ async fn delete(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ server_url: &str,
+ ) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ DELETE FROM mcp_servers
+ WHERE user_id = $1 AND url = $2
+ "#,
+ user_id.as_ref(),
+ server_url,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+
+ async fn list(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<McpServerRecord>, Self::Err> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT user_id, url, server_name, credentials, enabled
+ FROM mcp_servers
+ WHERE user_id = $1
+ ORDER BY created_at
+ "#,
+ user_id.as_ref(),
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ rows.into_iter()
+ .map(|r| self.to_record(r.user_id, r.url, r.server_name, r.credentials, r.enabled))
+ .collect()
+ }
+}
+
+impl PgServerRepo {
+ fn to_record(
+ &self,
+ user_id: String,
+ url: String,
+ server_name: String,
+ credentials: Option<Vec<u8>>,
+ enabled: bool,
+ ) -> Result<McpServerRecord, sqlx::Error> {
+ let user_id = MacroUserIdStr::parse_from_str(&user_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned();
+
+ let credentials = credentials.map(|c| self.decrypt(&c)).transpose()?;
+
+ Ok(McpServerRecord {
+ user_id,
+ url,
+ server_name,
+ credentials,
+ enabled,
+ })
+ }
+}
diff --git a/rust/cloud-storage/mcp_client/src/outbound/redis_state_store.rs b/rust/cloud-storage/mcp_client/src/outbound/redis_state_store.rs
new file mode 100644
index 0000000000..3eafa8540a
--- /dev/null
+++ b/rust/cloud-storage/mcp_client/src/outbound/redis_state_store.rs
@@ -0,0 +1,47 @@
+use crate::domain::ports::{OAuthStateStore, PendingAuth};
+use redis::AsyncCommands;
+use std::sync::Arc;
+
+const KEY_PREFIX: &str = "mcp:pending_auth:";
+const TTL_SECONDS: u64 = 600;
+
+/// Redis-backed [`OAuthStateStore`] with a 10-minute TTL.
+#[derive(Clone)]
+pub struct RedisOAuthStateStore {
+ client: Arc<redis::Client>,
+}
+
+impl RedisOAuthStateStore {
+ /// Create a new store from an existing Redis client.
+ pub fn new(client: Arc<redis::Client>) -> Self {
+ Self { client }
+ }
+}
+
+impl OAuthStateStore for RedisOAuthStateStore {
+ async fn save(&self, csrf_token: &str, pending: PendingAuth) -> anyhow::Result<()> {
+ let key = format!("{KEY_PREFIX}{csrf_token}");
+ let value = serde_json::to_string(&pending)?;
+ let mut conn = self
+ .client
+ .get_multiplexed_async_connection()
+ .await
+ .map_err(|e| anyhow::anyhow!("redis connection failed: {e}"))?;
+ conn.set_ex::<_, _, ()>(&key, &value, TTL_SECONDS).await?;
+ Ok(())
+ }
+
+ async fn take(&self, csrf_token: &str) -> anyhow::Result<Option<PendingAuth>> {
+ let key = format!("{KEY_PREFIX}{csrf_token}");
+ let mut conn = self
+ .client
+ .get_multiplexed_async_connection()
+ .await
+ .map_err(|e| anyhow::anyhow!("redis connection failed: {e}"))?;
+ let value: Option<String> = conn.get_del(&key).await?;
+ value
+ .map(|v| serde_json::from_str(&v))
+ .transpose()
+ .map_err(Into::into)
+ }
+}
diff --git a/rust/cloud-storage/mcp_service/Cargo.toml b/rust/cloud-storage/mcp_service/Cargo.toml
index 0d4ea45b88..bba5225b88 100644
--- a/rust/cloud-storage/mcp_service/Cargo.toml
+++ b/rust/cloud-storage/mcp_service/Cargo.toml
@@ -40,7 +40,7 @@ notification = { path = "../notification", features = ["ai_tool"] }
properties = { path = "../properties", features = ["ai_tools"] }
readonly_pool = { path = "../readonly_pool" }
redis = { workspace = true, features = ["aio", "tokio-comp"] }
-rmcp = { version = "1.2.0", features = ["transport-streamable-http-server"] }
+rmcp = { workspace = true, features = ["transport-streamable-http-server"] }
search_service_client = { path = "../search_service_client" }
secretsmanager_client = { path = "../secretsmanager_client" }
serde_json = { workspace = true }
diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rs
index cf3569683c..5222ea3478 100644
--- a/rust/cloud-storage/mcp_service/src/context.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -283,7 +283,7 @@ async fn build_tool_context(
let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(
chat::domain::service::ChatServiceImpl::new(
chat::outbound::postgres::PgChatRepo::new(db.clone()),
- Arc::new(ai_toolset::AsyncToolSet::new()),
+ Arc::new(ai_toolset::AsyncToolCollection::new()),
(),
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
entity_access_management::outbound::PgRepository::new(db.clone()),
diff --git a/rust/cloud-storage/mcp_service/src/main.rs b/rust/cloud-storage/mcp_service/src/main.rs
index 27e3af96ad..a9a889df99 100644
--- a/rust/cloud-storage/mcp_service/src/main.rs
+++ b/rust/cloud-storage/mcp_service/src/main.rs
@@ -38,11 +38,10 @@ async fn main() -> anyhow::Result<()> {
},
Arc::new(LocalSessionManager::default()),
{
- StreamableHttpServerConfig {
- stateful_mode: false,
- json_response: true,
- ..Default::default()
- }
+ let mut config = StreamableHttpServerConfig::default();
+ config.stateful_mode = false;
+ config.json_response = true;
+ config
},
);
diff --git a/rust/cloud-storage/mcp_service/src/tool_service.rs b/rust/cloud-storage/mcp_service/src/tool_service.rs
index fe36ce008d..993c09a949 100644
--- a/rust/cloud-storage/mcp_service/src/tool_service.rs
+++ b/rust/cloud-storage/mcp_service/src/tool_service.rs
@@ -1,4 +1,4 @@
-use ai_toolset::{AsyncToolSet, RequestContext};
+use ai_toolset::{AsyncToolCollection, RequestContext, ToolSet};
use macro_user_id::user_id::MacroUserIdStr;
use rmcp::{
handler::server::ServerHandler,
@@ -11,13 +11,13 @@ use std::sync::Arc;
/// MCP server handler that extracts authenticated user identity from HTTP
/// request parts injected by rmcp's `StreamableHttpService`.
pub struct AuthenticatedToolService<Context> {
- toolset: Arc<AsyncToolSet<Context>>,
+ toolset: Arc<AsyncToolCollection<Context>>,
context: Context,
}
impl<Context> AuthenticatedToolService<Context> {
/// Creates a new authenticated tool service.
- pub fn new(toolset: Arc<AsyncToolSet<Context>>, context: Context) -> Self {
+ pub fn new(toolset: Arc<AsyncToolCollection<Context>>, context: Context) -> Self {
Self { toolset, context }
}
}
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rs
index 3c9ea6e937..50967c3f8e 100644
--- a/rust/cloud-storage/memory/src/context.rs
+++ b/rust/cloud-storage/memory/src/context.rs
@@ -189,7 +189,7 @@ pub async fn build_tool_service_context(
let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(
chat::domain::service::ChatServiceImpl::new(
chat::outbound::postgres::PgChatRepo::new(pool.clone()),
- Arc::new(ai_toolset::AsyncToolSet::new()),
+ Arc::new(ai_toolset::AsyncToolCollection::new()),
(),
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
entity_access_management::outbound::PgRepository::new(pool.clone()),
diff --git a/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs b/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs
index 2d43c74290..8fbe66afd7 100644
--- a/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs
+++ b/rust/cloud-storage/notification/src/inbound/ai_tool/mod.rs
@@ -14,7 +14,7 @@ use crate::domain::{
service::NotificationReader,
};
use ai::tool::{
- AsyncTool, AsyncToolSet, RequestContext, ServiceContext, ToolCallError, ToolResult,
+ AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolCallError, ToolResult,
};
use async_trait::async_trait;
use cowlike::CowLike;
@@ -50,11 +50,11 @@ impl<T: NotificationReader> NotificationToolContext<T> {
}
/// Create a notification toolset for AI agents
-pub fn notification_toolset<T>() -> AsyncToolSet<NotificationToolContext<T>>
+pub fn notification_toolset<T>() -> AsyncToolCollection<NotificationToolContext<T>>
where
T: NotificationReader,
{
- AsyncToolSet::new()
+ AsyncToolCollection::new()
.add_tool::<ListNotifications, NotificationToolContext<T>>()
.add_tool::<MarkNotificationsSeen, NotificationToolContext<T>>()
.add_tool::<MarkNotificationsDone, NotificationToolContext<T>>()
diff --git a/rust/cloud-storage/properties/src/inbound/toolset/mod.rs b/rust/cloud-storage/properties/src/inbound/toolset/mod.rs
index 1619a9975f..11260563f3 100644
--- a/rust/cloud-storage/properties/src/inbound/toolset/mod.rs
+++ b/rust/cloud-storage/properties/src/inbound/toolset/mod.rs
@@ -7,7 +7,7 @@ mod set_entity_property;
mod test;
use crate::domain::service::PropertiesService;
-use ai::tool::AsyncToolSet;
+use ai::tool::AsyncToolCollection;
use std::sync::Arc;
pub use get_entity_properties::{GetEntityProperties, GetEntityPropertiesResponse};
@@ -37,11 +37,11 @@ impl<T: PropertiesService> PropertiesToolContext<T> {
}
/// Create a properties toolset.
-pub fn properties_toolset<T>() -> AsyncToolSet<PropertiesToolContext<T>>
+pub fn properties_toolset<T>() -> AsyncToolCollection<PropertiesToolContext<T>>
where
T: PropertiesService,
{
- AsyncToolSet::new()
+ AsyncToolCollection::new()
.add_tool::<GetEntityProperties, PropertiesToolContext<T>>()
.add_tool::<SetEntityProperty, PropertiesToolContext<T>>()
}
diff --git a/rust/cloud-storage/soup/src/inbound/toolset/mod.rs b/rust/cloud-storage/soup/src/inbound/toolset/mod.rs
index 7c87d0f625..ea6efdb0ae 100644
--- a/rust/cloud-storage/soup/src/inbound/toolset/mod.rs
+++ b/rust/cloud-storage/soup/src/inbound/toolset/mod.rs
@@ -6,7 +6,7 @@ mod list_entities;
mod test;
use crate::domain::ports::SoupService;
-use ai::tool::AsyncToolSet;
+use ai::tool::AsyncToolCollection;
use email::domain::ports::EmailService;
use std::sync::Arc;
@@ -40,10 +40,10 @@ impl<T: SoupService, E: EmailService> SoupToolContext<T, E> {
}
/// Create a soup toolset
-pub fn soup_toolset<T, E>() -> AsyncToolSet<SoupToolContext<T, E>>
+pub fn soup_toolset<T, E>() -> AsyncToolCollection<SoupToolContext<T, E>>
where
T: SoupService,
E: EmailService,
{
- AsyncToolSet::new().add_tool::<ListEntities, SoupToolContext<T, E>>()
+ AsyncToolCollection::new().add_tool::<ListEntities, SoupToolContext<T, E>>()
}