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(mcp): let agents connect a custom MCP server (#7869)

Wolf Mermelstein7ebaba1e9637
diff --git a/Cargo.lock b/Cargo.lock
index 13f7661f82..268d794ae7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -12604,6 +12604,7 @@ dependencies = [
"thiserror 2.0.18",
"tokio",
"tracing",
+ "url",
"utoipa",
"workspace-hack",
]
diff --git a/apps/web/src/features/block-agent/state/tool-approval-wording.ts b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
index eb9a7595d6..96e5a60b29 100644
--- a/apps/web/src/features/block-agent/state/tool-approval-wording.ts
+++ b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
@@ -24,6 +24,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
CommentOnText: (whose) => `comment on ${whose} documents`,
ConfigureAgent: (whose) => `change ${whose} agents`,
ConfigureBot: (whose) => `change ${whose} bots`,
+ ConnectMcpServer: (whose) => `connect an MCP server to ${whose} account`,
ContentSearch: (whose) => `search ${whose} workspace`,
CreateBookingLink: (whose) => `create a booking link for ${whose} calendar`,
CreateBot: (whose) => `create a bot in ${whose} workspace`,
diff --git a/apps/web/src/lib/core/component/AI/component/tool/ConnectMcpServer.tsx b/apps/web/src/lib/core/component/AI/component/tool/ConnectMcpServer.tsx
new file mode 100644
index 0000000000..61c61a3b91
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/ConnectMcpServer.tsx
@@ -0,0 +1,49 @@
+import Plug from '@phosphor-icons/core/regular/plug.svg';
+import { createSignal } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { DetailPanel } from './Bots';
+import { Tool } from './Tool';
+import { createToolRenderer } from './ToolRenderer';
+
+export const connectMcpServerHandler = createToolRenderer({
+ name: 'ConnectMcpServer',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const response = () => ctx.response?.data;
+
+ return (
+ <BaseTool
+ icon={Plug}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() && response() ? (
+ <DetailPanel
+ summary={response()!.summary}
+ details={[
+ { label: 'URL', value: response()!.url },
+ {
+ label: 'Signed in',
+ value: response()!.authenticated ? 'Yes' : 'No',
+ },
+ { label: 'Enabled', value: response()!.enabled ? 'Yes' : 'No' },
+ ]}
+ />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span>
+ {ctx.response ? 'Connected MCP server' : 'Connect MCP server'}
+ </span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!response()}
+ status={response()?.serverName}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
index a9a14d14bc..478fbcfee8 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
@@ -94,6 +94,7 @@ import {
readDiscussionHandler,
resolveCommentHandler,
} from './Comments';
+import { connectMcpServerHandler } from './ConnectMcpServer';
import { createDocumentHandler } from './CreateDocument';
import { createProjectHandler } from './CreateProject';
import { createSkillHandler } from './CreateSkill';
@@ -268,6 +269,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
ImportFromLinear: importFromLinearHandler,
ImportFromJira: importFromJiraHandler,
ImportNotionPage: importNotionPageHandler,
+ ConnectMcpServer: connectMcpServerHandler,
GetCompany: getCompanyHandler,
CreateCompany: createCompanyHandler,
CreateContact: createContactHandler,
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts b/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
index 5716311bc0..eede3d843f 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
@@ -1768,13 +1768,19 @@ export const updateMcpServer = async (
};
/**
- * @summary Add a new MCP server for the authenticated user.
+ * @summary Add a new MCP server for the authenticated user. A URL the user already
+has is returned as stored, keeping its credentials.
*/
export type addMcpServerResponse201 = {
data: ServerResponse;
status: 201;
};
+export type addMcpServerResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
export type addMcpServerResponse401 = {
data: string;
status: 401;
@@ -1789,6 +1795,7 @@ export type addMcpServerResponseSuccess = addMcpServerResponse201 & {
headers: Headers;
};
export type addMcpServerResponseError = (
+ | addMcpServerResponse400
| addMcpServerResponse401
| addMcpServerResponse500
) & {
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index 54e5838485..bcb3ea3526 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -1316,6 +1316,20 @@ export const ConfigureBotResponse = z.object({
summary: z.string(),
});
+export const ConnectMcpServer = z.object({
+ url: z.string(),
+ serverName: z.string(),
+});
+
+export const ConnectMcpServerResponse = z.object({
+ url: z.string(),
+ serverName: z.string(),
+ alreadyConnected: z.boolean(),
+ authenticated: z.boolean(),
+ enabled: z.boolean(),
+ summary: z.string(),
+});
+
export const ContentSearch = z.object({
query: z.string(),
matchType: z
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
index fe460b645a..ba7a67c3ec 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
@@ -47,6 +47,10 @@ type ToolParserMap = {
call: types.ConfigureBot;
response: types.ConfigureBotResponse;
};
+ ConnectMcpServer: {
+ call: types.ConnectMcpServer;
+ response: types.ConnectMcpServerResponse;
+ };
ContentSearch: {
call: types.ContentSearch;
response: types.SearchToolResponse;
@@ -589,6 +593,10 @@ const toolParserMap = {
call: schemas.ConfigureBot,
response: schemas.ConfigureBotResponse,
},
+ ConnectMcpServer: {
+ call: schemas.ConnectMcpServer,
+ response: schemas.ConnectMcpServerResponse,
+ },
ContentSearch: {
call: schemas.ContentSearch,
response: schemas.SearchToolResponse,
@@ -1202,6 +1210,10 @@ type ToolDataMap = {
call: types.ConfigureBot;
response: types.ConfigureBotResponse;
};
+ ConnectMcpServer: {
+ call: types.ConnectMcpServer;
+ response: types.ConnectMcpServerResponse;
+ };
ContentSearch: {
call: types.ContentSearch;
response: types.SearchToolResponse;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index f094a74eae..1bd9081f86 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -6242,6 +6242,48 @@ export interface ConfigureBotResponse {
*/
summary: string;
}
+/**
+ * Add a remote MCP server to the current user's connections by its URL, so their agents and chats can use its tools. Use when the user asks to connect, add, or install an MCP server they give you the URL of, or one whose official remote MCP URL you are sure of; never guess a URL. Most servers need the user to sign in afterwards: when the result says so, tell them to open Settings → Connections and click Connect next to the server. Its tools are available in new conversations once connected. A URL the user already has is left as it is.
+ */
+export interface ConnectMcpServer {
+ /**
+ * The MCP server's streamable HTTP URL, e.g. `https://mcp.linear.app/mcp`. Must be https on a public host.
+ */
+ url: string;
+ /**
+ * Short display name for the server, e.g. `Linear`. Its tools are listed under this name.
+ */
+ serverName: string;
+}
+/**
+ * Response from [`ConnectMcpServer`].
+ */
+export interface ConnectMcpServerResponse {
+ /**
+ * The server's URL.
+ */
+ url: string;
+ /**
+ * The server's display name.
+ */
+ serverName: string;
+ /**
+ * Whether the user already had this server before the call.
+ */
+ alreadyConnected: boolean;
+ /**
+ * Whether the server holds the user's sign-in.
+ */
+ authenticated: boolean;
+ /**
+ * Whether the server's tools are turned on.
+ */
+ enabled: boolean;
+ /**
+ * What happened and what the user still has to do.
+ */
+ summary: string;
+}
/**
* Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; agent session messages; call transcripts. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed content. Use this for targeted keyword/content lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. Whitespace-separated terms are ANDed. For documents and emails, every term must match somewhere in the document — different terms can appear in different chunks/pages or different fields. For documents and emails specifically, each single-word term is matched as a prefix (so `scri` matches `script`); for emails the prefix expansion also runs against the local-part of address fields. For agent sessions, channels, and call transcripts the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the content, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion (e.g. an exact word, identifier, or full email address). Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, projects, and call records include the tags visible to the user as {label, scope} pairs; to restrict a search to tagged items, pass the tag labels in the tags argument (ListTags shows which tags exist).
*/
diff --git a/apps/web/src/lib/service-clients/service-cognition/openapi.json b/apps/web/src/lib/service-clients/service-cognition/openapi.json
index c3073698b8..f04228adf9 100644
--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json
+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json
@@ -1444,7 +1444,7 @@
},
"post": {
"tags": ["mcp"],
- "summary": "Add a new MCP server for the authenticated user.",
+ "summary": "Add a new MCP server for the authenticated user. A URL the user already\nhas is returned as stored, keeping its credentials.",
"operationId": "add_mcp_server",
"requestBody": {
"content": {
@@ -1467,6 +1467,16 @@
}
}
},
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"401": {
"description": "",
"content": {
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index d487d56018..ec9236c68a 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -649,6 +649,12 @@ pub async fn build_tool_service_context_from_env(
} else {
ToolImportToolContext::unwired()
};
+ let mcp_server_tool_context = match &native_servers {
+ Some(native_servers) => crate::tool_context::ToolMcpServerToolContext::wired(
+ mcp_client::domain::service::ServerDirectory::new(native_servers.clone()),
+ ),
+ None => crate::tool_context::ToolMcpServerToolContext::unwired(),
+ };
Ok(ToolServiceContext {
connector_tool_context: crate::tool_context::build_connector_tool_context(
@@ -701,6 +707,7 @@ pub async fn build_tool_service_context_from_env(
forms_tool_context,
databases_sql_tool_context,
import_tool_context,
+ mcp_server_tool_context,
chat_tool_context,
channel_tool_context,
channel_media_upload_tool_context: crate::build_channel_media_upload_tool_context()?,
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index 553cae1091..f7f670fe46 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -50,6 +50,7 @@ use email::inbound::toolset::{email_toolset, mcp_toolset as email_mcp_toolset};
use favorites::inbound::toolset::favorites_toolset;
use import::inbound::toolset::import_toolset;
use initiative::inbound::toolset::initiative_toolset;
+use mcp_client::inbound::toolset::mcp_server_toolset;
use messages::inbound::toolset::message_toolset;
use notification::inbound::ai_tool::{item_notification_preference_toolset, notification_toolset};
use projects::inbound::toolset::project_toolset;
@@ -91,12 +92,13 @@ pub use tool_context::{
ToolFavoritesService, ToolFavoritesToolContext, ToolForeignEntityService, ToolFormsToolContext,
ToolFrecencyService, ToolGithubPullRequestService, ToolImageGenerationToolContext,
ToolImportService, ToolImportToolContext, ToolInitiativeToolContext,
- ToolItemNotificationPreferenceToolContext, ToolMcpSelector, ToolMessageToolContext,
- ToolNotificationQueue, ToolNotificationService, ToolNotificationToolContext,
- ToolPipedreamConnection, ToolPipelineService, ToolPipelineToolContext, ToolPipelineWorkflows,
- ToolProjectService, ToolProjectToolContext, ToolPropertiesService, ToolPropertiesToolContext,
- ToolReadAgentSessionContext, ToolServiceContext, ToolSkillService, ToolSkillToolContext,
- ToolSoupService, ToolSystemPropertiesService, ToolTableEventPublisher, ToolTeamCalendarService,
+ ToolItemNotificationPreferenceToolContext, ToolMcpSelector, ToolMcpServerToolContext,
+ ToolMessageToolContext, ToolNotificationQueue, ToolNotificationService,
+ ToolNotificationToolContext, ToolPipedreamConnection, ToolPipelineService,
+ ToolPipelineToolContext, ToolPipelineWorkflows, ToolProjectService, ToolProjectToolContext,
+ ToolPropertiesService, ToolPropertiesToolContext, ToolReadAgentSessionContext,
+ ToolServiceContext, ToolSkillService, ToolSkillToolContext, ToolSoupService,
+ ToolSystemPropertiesService, ToolTableEventPublisher, ToolTeamCalendarService,
ToolTeamCalendarToolContext, ToolTeamService, ToolTeamToolContext, ToolUserEmailService,
ToolViewOnlyDatabasesSqlToolContext, build_activity_tool_context,
build_booking_link_tool_context, build_booking_management_tool_context, build_bot_tool_context,
@@ -308,6 +310,15 @@ fn tools_for_inner(host: AiHost, code_mode_direct: bool) -> ToolSetWithPrompt {
.add_subtoolset::<ToolImportToolContext>(import_toolset())
.add_subtoolset::<ToolCodingAgentToolContext>(coding_agent_toolset())
.add_tool::<Subagent, SubagentContext>();
+ // Only Macro's own agents connect servers for the user.
+ let toolset = match host {
+ AiHost::Chat | AiHost::AgentSession => {
+ toolset.add_subtoolset::<ToolMcpServerToolContext>(mcp_server_toolset::<
+ mcp_client::outbound::pg_server_repo::PgServerRepo,
+ >())
+ }
+ AiHost::ChannelBot | AiHost::Mcp => toolset,
+ };
let toolset = match host {
AiHost::Chat | AiHost::AgentSession | AiHost::ChannelBot => toolset
.add_tool::<SearchTools, ToolServiceContext>()
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index ddae90aaae..553e90dc39 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -1931,6 +1931,12 @@ pub type ToolImportService = import::domain::service::ImportServiceImpl<
>,
>;
+/// The custom MCP server tools, wired by hosts holding the MCP credentials
+/// key.
+pub type ToolMcpServerToolContext = mcp_client::inbound::toolset::McpServerToolContext<
+ mcp_client::outbound::pg_server_repo::PgServerRepo,
+>;
+
/// Type alias for the import tool context, wired by hosts with connector access.
pub type ToolImportToolContext = import::inbound::toolset::ImportToolContext<ToolImportService>;
@@ -2008,6 +2014,9 @@ pub struct ToolServiceContext {
/// Import staging/tracking tools. `unwired` in hosts that can't build
/// the import service — calls there fail with a clear error.
pub import_tool_context: ToolImportToolContext,
+ /// Custom MCP server tools. `unwired` in hosts without the MCP
+ /// credentials key — calls there fail with a clear error.
+ pub mcp_server_tool_context: ToolMcpServerToolContext,
/// Built per-request via a manual `FromRef` below so it can carry the
/// running chat's id — the derive's field-clone would freeze it at
/// startup with no chat id set.
diff --git a/crates/mcp_client/AGENTS.md b/crates/mcp_client/AGENTS.md
index 72c3417343..a7b11cd823 100644
--- a/crates/mcp_client/AGENTS.md
+++ b/crates/mcp_client/AGENTS.md
@@ -8,22 +8,27 @@ ones) and executes their tools for agents.
## How it works
-A user connects a server through the HTTP routes (OAuth callback if needed);
-the server config and OAuth tokens are stored via the outbound adapters
-(Postgres, Redis). When an agent calls one of that server's tools, the
+A user connects a server through the HTTP routes, or an agent adds one with
+the `ConnectMcpServer` AI tool and the user signs in afterwards (OAuth
+callback if needed). Both paths go through `ServerDirectory`, which only lets
+agents add public `https` destinations. The server config and OAuth tokens
+are stored via the outbound adapters (Postgres, Redis). When an agent calls one of that server's tools, the
service orchestration layer looks up the connection and executes the tool
through `rmcp`, returning the result to the caller's tool-calling loop.
## Start here
- `src/domain/service/`: connection/tool-execution orchestration
- (`toolset.rs`, `server_access.rs`, `persisting_credential_store.rs`).
+ (`toolset.rs`, `server_access.rs`, `persisting_credential_store.rs`), and
+ `server_directory.rs` for adding servers.
- `src/domain/ports.rs`: `McpServerStore`, `OAuthStateStore`, and the OAuth
port the outbound adapters implement.
- `src/domain/provider_registry.rs` (feature `providers`): pre-registered
OAuth credentials for known MCP providers, keyed off `macro_env_var`.
- `src/inbound/axum_router.rs`: HTTP routes for server management and the
OAuth callback.
+- `src/inbound/toolset.rs`: the `ConnectMcpServer` AI tool, wired through
+ `ai_tools` where the MCP credentials key is configured.
- `src/outbound/`: `oauth.rs` (RMCP-backed OAuth), `pg_server_repo.rs`
(Postgres server store), `redis_state_store.rs` (OAuth state).
@@ -54,6 +59,10 @@ through `rmcp`, returning the result to the caller's tool-calling loop.
- OAuth state lives in Redis (`redis_state_store.rs`) separately from the
server config in Postgres (`pg_server_repo.rs`) — a server record surviving
doesn't mean its OAuth state did.
+- `ServerDirectory`'s public-destination check for agent-added servers judges
+ hostnames by name and never resolves them, so a public name that resolves
+ to a private address passes. Protection against that belongs where the
+ backend connects, for every stored server.
## Related
diff --git a/crates/mcp_client/Cargo.toml b/crates/mcp_client/Cargo.toml
index 2561596b7a..2b9e726dbd 100644
--- a/crates/mcp_client/Cargo.toml
+++ b/crates/mcp_client/Cargo.toml
@@ -34,6 +34,7 @@ serde_json.workspace = true
sqlx.workspace = true
thiserror.workspace = true
tracing.workspace = true
+url.workspace = true
utoipa.workspace = true
workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/mcp_client/src/domain/service/mod.rs b/crates/mcp_client/src/domain/service/mod.rs
index 5b7a6bf465..b27df76ee5 100644
--- a/crates/mcp_client/src/domain/service/mod.rs
+++ b/crates/mcp_client/src/domain/service/mod.rs
@@ -3,9 +3,12 @@ pub mod persisting_credential_store;
/// A live credential for a stored server, for callers that stamp headers
/// themselves.
pub mod server_access;
+/// Adding custom MCP servers to a user's connections.
+pub mod server_directory;
/// MCP tool set and combined tool set for the AI loop.
pub mod toolset;
pub use persisting_credential_store::PersistingCredentialStore;
pub use server_access::{ServerAccess, server_access, unexpired_access_token};
+pub use server_directory::{AddServerError, AddedBy, AddedServer, ServerDirectory};
pub use toolset::{CombinedToolSet, McpToolSet};
diff --git a/crates/mcp_client/src/domain/service/server_directory.rs b/crates/mcp_client/src/domain/service/server_directory.rs
new file mode 100644
index 0000000000..f0b70b29c5
--- /dev/null
+++ b/crates/mcp_client/src/domain/service/server_directory.rs
@@ -0,0 +1,186 @@
+//! Adding custom MCP servers to a user's connections.
+//!
+//! The settings dialog and the `ConnectMcpServer` AI tool both add servers
+//! through here, so a server added either way is the same row.
+
+use crate::domain::models::{MacroUserIdStr, McpServerRecord};
+use crate::domain::ports::McpServerStore;
+use std::net::{Ipv4Addr, Ipv6Addr};
+use std::sync::Arc;
+use url::{Host, Url};
+
+#[cfg(test)]
+mod test;
+
+/// Why a server could not be added.
+#[derive(Debug, thiserror::Error)]
+pub enum AddServerError {
+ /// The URL is not an absolute `http` or `https` URL.
+ #[error("`{0}` is not an http(s) URL")]
+ InvalidUrl(String),
+ /// An agent named a destination it may not add: not `https`, or not on
+ /// the public internet.
+ #[error("`{0}` is not a public https URL")]
+ NonPublicDestination(String),
+ /// The server name is empty.
+ #[error("the server name is empty")]
+ EmptyName,
+ /// The store failed.
+ #[error(transparent)]
+ Store(anyhow::Error),
+}
+
+/// Who is adding a server, which decides the destinations allowed.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AddedBy {
+ /// The user, by URL in settings.
+ User,
+ /// An agent acting for the user. The backend later connects to the URL,
+ /// so an agent may only add public `https` destinations: a prompt must
+ /// not be able to aim Macro at loopback, private or link-local hosts.
+ Agent,
+}
+
+/// A server added by [`ServerDirectory::add`].
+#[derive(Debug)]
+pub enum AddedServer {
+ /// The user had no server at this URL; it is stored now, without
+ /// credentials.
+ New(McpServerRecord),
+ /// The user already had this URL, so the stored row is left untouched.
+ Existing(McpServerRecord),
+}
+
+impl AddedServer {
+ /// The stored row.
+ pub fn record(&self) -> &McpServerRecord {
+ match self {
+ Self::New(record) | Self::Existing(record) => record,
+ }
+ }
+}
+
+/// A user's custom MCP servers.
+pub struct ServerDirectory<Store> {
+ store: Arc<Store>,
+}
+
+impl<Store> Clone for ServerDirectory<Store> {
+ fn clone(&self) -> Self {
+ Self {
+ store: self.store.clone(),
+ }
+ }
+}
+
+impl<Store> ServerDirectory<Store>
+where
+ Store: McpServerStore,
+ anyhow::Error: From<Store::Err>,
+{
+ /// A directory over `store`.
+ pub fn new(store: Arc<Store>) -> Self {
+ Self { store }
+ }
+
+ /// Add `url` to `user_id`'s servers under `server_name`, enabled and
+ /// without credentials; the user signs in afterwards through OAuth.
+ ///
+ /// A URL the user already has is returned as stored. Saving over it
+ /// would wipe the grant it holds.
+ #[tracing::instrument(skip(self), err)]
+ pub async fn add(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ url: &str,
+ server_name: &str,
+ added_by: AddedBy,
+ ) -> Result<AddedServer, AddServerError> {
+ let url = url.trim();
+ let server_name = server_name.trim();
+ let parsed = match Url::parse(url) {
+ Ok(parsed) if matches!(parsed.scheme(), "http" | "https") => parsed,
+ _ => return Err(AddServerError::InvalidUrl(url.to_owned())),
+ };
+ if added_by == AddedBy::Agent && !is_public_https(&parsed) {
+ return Err(AddServerError::NonPublicDestination(url.to_owned()));
+ }
+ if server_name.is_empty() {
+ return Err(AddServerError::EmptyName);
+ }
+
+ if let Some(existing) = self
+ .store
+ .load(&user_id, url)
+ .await
+ .map_err(|error| AddServerError::Store(error.into()))?
+ {
+ return Ok(AddedServer::Existing(existing));
+ }
+
+ let record = McpServerRecord {
+ user_id,
+ url: url.to_owned(),
+ server_name: server_name.to_owned(),
+ credentials: None,
+ enabled: true,
+ };
+ self.store
+ .save(&record)
+ .await
+ .map_err(|error| AddServerError::Store(error.into()))?;
+ Ok(AddedServer::New(record))
+ }
+}
+
+/// Whether `url` is `https` to a host on the public internet.
+///
+/// Hostnames are judged by name only: `localhost` and `.localhost`,
+/// `.local` and `.internal` names are refused, while a public-looking name
+/// is not resolved here.
+fn is_public_https(url: &Url) -> bool {
+ if url.scheme() != "https" {
+ return false;
+ }
+ match url.host() {
+ Some(Host::Domain(domain)) => {
+ let domain = domain.trim_end_matches('.').to_ascii_lowercase();
+ !(domain == "localhost"
+ || domain.ends_with(".localhost")
+ || domain.ends_with(".local")
+ || domain.ends_with(".internal"))
+ }
+ Some(Host::Ipv4(address)) => is_public_ipv4(address),
+ Some(Host::Ipv6(address)) => is_public_ipv6(address),
+ None => false,
+ }
+}
+
+fn is_public_ipv4(address: Ipv4Addr) -> bool {
+ let [first, second, ..] = address.octets();
+ !(address.is_unspecified()
+ || address.is_loopback()
+ || address.is_private()
+ || address.is_link_local()
+ || address.is_broadcast()
+ || address.is_documentation()
+ || address.is_multicast()
+ // Carrier-grade NAT, 100.64.0.0/10.
+ || (first == 100 && (second & 0b1100_0000) == 64)
+ // "This network", 0.0.0.0/8.
+ || first == 0)
+}
+
+fn is_public_ipv6(address: Ipv6Addr) -> bool {
+ if let Some(mapped) = address.to_ipv4_mapped() {
+ return is_public_ipv4(mapped);
+ }
+ let first = address.segments()[0];
+ !(address.is_unspecified()
+ || address.is_loopback()
+ || address.is_multicast()
+ // Unique local, fc00::/7.
+ || (first & 0xfe00) == 0xfc00
+ // Link-local, fe80::/10.
+ || (first & 0xffc0) == 0xfe80)
+}
diff --git a/crates/mcp_client/src/domain/service/server_directory/test.rs b/crates/mcp_client/src/domain/service/server_directory/test.rs
new file mode 100644
index 0000000000..0547f64207
--- /dev/null
+++ b/crates/mcp_client/src/domain/service/server_directory/test.rs
@@ -0,0 +1,209 @@
+use super::*;
+use crate::domain::models::StoredCredentials;
+use macro_user_id::cowlike::CowLike;
+use std::sync::Mutex;
+
+/// In-memory [`McpServerStore`] keyed by user and URL.
+#[derive(Default)]
+struct FakeServerStore {
+ records: Mutex<Vec<McpServerRecord>>,
+}
+
+impl McpServerStore for FakeServerStore {
+ type Err = anyhow::Error;
+
+ async fn save(&self, record: &McpServerRecord) -> Result<(), Self::Err> {
+ let mut records = self.records.lock().unwrap();
+ records.retain(|stored| !(stored.user_id == record.user_id && stored.url == record.url));
+ records.push(record.clone());
+ Ok(())
+ }
+
+ async fn load(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ server_url: &str,
+ ) -> Result<Option<McpServerRecord>, Self::Err> {
+ Ok(self
+ .records
+ .lock()
+ .unwrap()
+ .iter()
+ .find(|stored| &stored.user_id == user_id && stored.url == server_url)
+ .cloned())
+ }
+
+ async fn delete(
+ &self,
+ _user_id: &MacroUserIdStr<'static>,
+ _server_url: &str,
+ ) -> Result<(), Self::Err> {
+ unimplemented!()
+ }
+
+ async fn list(
+ &self,
+ _user_id: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<McpServerRecord>, Self::Err> {
+ unimplemented!()
+ }
+}
+
+fn owner() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned()
+}
+
+#[tokio::test]
+async fn a_new_url_is_stored_enabled_and_without_credentials() {
+ let store = Arc::new(FakeServerStore::default());
+ let directory = ServerDirectory::new(store.clone());
+
+ let added = directory
+ .add(
+ owner(),
+ " https://mcp.linear.app/mcp ",
+ " Linear ",
+ AddedBy::User,
+ )
+ .await
+ .unwrap();
+
+ let AddedServer::New(record) = added else {
+ panic!("expected a new server, got {added:?}");
+ };
+ assert_eq!(record.url, "https://mcp.linear.app/mcp");
+ assert_eq!(record.server_name, "Linear");
+ assert!(record.enabled);
+ assert!(record.credentials.is_none());
+ let stored = store
+ .load(&owner(), "https://mcp.linear.app/mcp")
+ .await
+ .unwrap()
+ .expect("the server is stored");
+ assert_eq!(stored.server_name, "Linear");
+}
+
+#[tokio::test]
+async fn re_adding_a_url_keeps_the_grant_it_holds() {
+ let store = Arc::new(FakeServerStore::default());
+ store
+ .save(&McpServerRecord {
+ user_id: owner(),
+ url: "https://mcp.linear.app/mcp".to_owned(),
+ server_name: "Linear".to_owned(),
+ credentials: Some(StoredCredentials::new(
+ "client-id".to_owned(),
+ None,
+ Vec::new(),
+ Some(1_000),
+ )),
+ enabled: false,
+ })
+ .await
+ .unwrap();
+ let directory = ServerDirectory::new(store.clone());
+
+ let added = directory
+ .add(
+ owner(),
+ "https://mcp.linear.app/mcp",
+ "Renamed",
+ AddedBy::User,
+ )
+ .await
+ .unwrap();
+
+ let AddedServer::Existing(record) = added else {
+ panic!("expected the existing server, got {added:?}");
+ };
+ assert_eq!(record.server_name, "Linear");
+ assert!(!record.enabled);
+ assert!(record.credentials.is_some());
+}
+
+#[tokio::test]
+async fn a_url_that_is_not_http_is_refused() {
+ let directory = ServerDirectory::new(Arc::new(FakeServerStore::default()));
+
+ for url in ["linear", "file:///etc/passwd", "ftp://mcp.example.com"] {
+ let result = directory.add(owner(), url, "Linear", AddedBy::User).await;
+ assert!(
+ matches!(result, Err(AddServerError::InvalidUrl(_))),
+ "{url}: {result:?}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn an_empty_name_is_refused() {
+ let directory = ServerDirectory::new(Arc::new(FakeServerStore::default()));
+
+ let result = directory
+ .add(owner(), "https://mcp.linear.app/mcp", " ", AddedBy::User)
+ .await;
+
+ assert!(
+ matches!(result, Err(AddServerError::EmptyName)),
+ "{result:?}"
+ );
+}
+
+#[tokio::test]
+async fn an_agent_may_not_add_a_non_public_or_cleartext_destination() {
+ let store = Arc::new(FakeServerStore::default());
+ let directory = ServerDirectory::new(store.clone());
+
+ for url in [
+ "http://mcp.linear.app/mcp",
+ "https://localhost/mcp",
+ "https://tools.localhost/mcp",
+ "https://metadata.google.internal/mcp",
+ "https://printer.local/mcp",
+ "https://127.0.0.1/mcp",
+ "https://10.1.2.3/mcp",
+ "https://172.16.0.1/mcp",
+ "https://192.168.1.1/mcp",
+ "https://169.254.169.254/latest/meta-data",
+ "https://100.64.0.1/mcp",
+ "https://0.0.0.0/mcp",
+ "https://[::1]/mcp",
+ "https://[fd00::1]/mcp",
+ "https://[fe80::1]/mcp",
+ "https://[::ffff:127.0.0.1]/mcp",
+ ] {
+ let result = directory
+ .add(owner(), url, "Internal", AddedBy::Agent)
+ .await;
+ assert!(
+ matches!(result, Err(AddServerError::NonPublicDestination(_))),
+ "{url}: {result:?}"
+ );
+ }
+ assert!(store.records.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn an_agent_may_add_a_public_https_destination() {
+ let directory = ServerDirectory::new(Arc::new(FakeServerStore::default()));
+
+ for url in ["https://mcp.linear.app/mcp", "https://8.8.8.8/mcp"] {
+ let result = directory.add(owner(), url, "Public", AddedBy::Agent).await;
+ assert!(
+ matches!(result, Ok(AddedServer::New(_))),
+ "{url}: {result:?}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn a_user_may_still_add_a_cleartext_or_local_destination() {
+ let directory = ServerDirectory::new(Arc::new(FakeServerStore::default()));
+
+ let result = directory
+ .add(owner(), "http://localhost:8080/mcp", "Local", AddedBy::User)
+ .await;
+
+ assert!(matches!(result, Ok(AddedServer::New(_))), "{result:?}");
+}
diff --git a/crates/mcp_client/src/inbound/axum_router.rs b/crates/mcp_client/src/inbound/axum_router.rs
index f7e2c671a0..59a2e5f568 100644
--- a/crates/mcp_client/src/inbound/axum_router.rs
+++ b/crates/mcp_client/src/inbound/axum_router.rs
@@ -1,6 +1,7 @@
use crate::domain::{
models::{MacroUserIdStr, McpServerRecord, OAuthClientMetadata},
ports::{McpServerStore, OAuthClient},
+ service::{AddServerError, AddedBy, ServerDirectory},
};
use axum::{
Json, Router,
@@ -244,6 +245,9 @@ pub enum McpHandlerErr {
/// The requested server was not found.
#[error("server not found")]
NotFound,
+ /// The request was malformed.
+ #[error("{0}")]
+ InvalidRequest(String),
/// The OAuth provider rejected the authorization request.
#[error("authorization rejected by provider: {0}")]
OAuthRejected(String),
@@ -259,9 +263,9 @@ impl IntoResponse for McpHandlerErr {
fn into_response(self) -> axum::response::Response {
let status = match &self {
McpHandlerErr::NotFound => StatusCode::NOT_FOUND,
- McpHandlerErr::OAuthRejected(_) | McpHandlerErr::MalformedCallback => {
- StatusCode::BAD_REQUEST
- }
+ McpHandlerErr::InvalidRequest(_)
+ | McpHandlerErr::OAuthRejected(_)
+ | McpHandlerErr::MalformedCallback => StatusCode::BAD_REQUEST,
McpHandlerErr::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
(
@@ -319,11 +323,13 @@ where
request_body = AddServerRequest,
responses(
(status = 201, body = ServerResponse),
+ (status = 400, body = ErrorResponse),
(status = 401, body = String),
(status = 500, body = ErrorResponse),
)
)]
-/// Add a new MCP server for the authenticated user.
+/// Add a new MCP server for the authenticated user. A URL the user already
+/// has is returned as stored, keeping its credentials.
#[tracing::instrument(skip_all, err)]
pub async fn add_server<S, O, Auth>(
State(state): State<McpRouterState<S, O, Auth>>,
@@ -337,23 +343,24 @@ where
anyhow::Error: From<S::Err>,
{
let user = &authorization.authorization.user;
- let record = McpServerRecord {
- user_id: user.macro_user_id.clone(),
- url: body.url,
- server_name: body.server_name,
- credentials: None,
- enabled: true,
- };
-
- state
- .store
- .save(&record)
+ let added = ServerDirectory::new(state.store.clone())
+ .add(
+ user.macro_user_id.clone(),
+ &body.url,
+ &body.server_name,
+ AddedBy::User,
+ )
.await
- .map_err(anyhow::Error::from)?;
+ .map_err(|error| match error {
+ AddServerError::InvalidUrl(_)
+ | AddServerError::NonPublicDestination(_)
+ | AddServerError::EmptyName => McpHandlerErr::InvalidRequest(error.to_string()),
+ AddServerError::Store(error) => McpHandlerErr::Internal(error),
+ })?;
Ok((
StatusCode::CREATED,
- Json(ServerResponse::from_record(&record)),
+ Json(ServerResponse::from_record(added.record())),
))
}
diff --git a/crates/mcp_client/src/inbound/mod.rs b/crates/mcp_client/src/inbound/mod.rs
index d081a2eda7..9e1a84cf73 100644
--- a/crates/mcp_client/src/inbound/mod.rs
+++ b/crates/mcp_client/src/inbound/mod.rs
@@ -1,4 +1,6 @@
/// Axum HTTP adapter for MCP server management and OAuth callbacks.
pub mod axum_router;
+/// AI tools over the user's custom MCP servers.
+pub mod toolset;
pub use axum_router::{McpRouterState, mcp_oauth_callback_router, mcp_router};
diff --git a/crates/mcp_client/src/inbound/toolset.rs b/crates/mcp_client/src/inbound/toolset.rs
new file mode 100644
index 0000000000..83c9bd78aa
--- /dev/null
+++ b/crates/mcp_client/src/inbound/toolset.rs
@@ -0,0 +1,174 @@
+//! AI tools over the user's custom MCP servers.
+
+use crate::domain::ports::McpServerStore;
+use crate::domain::service::{AddServerError, AddedBy, AddedServer, ServerDirectory};
+use ai_toolset::{
+ AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations,
+ ToolCallError, ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+#[cfg(test)]
+mod test;
+
+/// Service context for the custom MCP server tools.
+///
+/// The directory is optional because the tool schemas ship with the shared
+/// chat toolset while only hosts holding the MCP credentials key can build
+/// the store. Where it is absent, calls fail with a clear error.
+pub struct McpServerToolContext<Store> {
+ /// The user's custom MCP servers, where the host wired them.
+ pub servers: Option<ServerDirectory<Store>>,
+}
+
+impl<Store> Clone for McpServerToolContext<Store> {
+ fn clone(&self) -> Self {
+ Self {
+ servers: self.servers.clone(),
+ }
+ }
+}
+
+impl<Store> McpServerToolContext<Store> {
+ /// A context whose tools add servers to `servers`.
+ pub fn wired(servers: ServerDirectory<Store>) -> Self {
+ Self {
+ servers: Some(servers),
+ }
+ }
+
+ /// A context with no server store: every tool call fails with a clear
+ /// error.
+ pub fn unwired() -> Self {
+ Self { servers: None }
+ }
+}
+
+/// The custom MCP server toolset.
+pub fn mcp_server_toolset<Store>() -> AsyncToolCollection<McpServerToolContext<Store>>
+where
+ Store: McpServerStore,
+ anyhow::Error: From<Store::Err>,
+{
+ AsyncToolCollection::new().add_tool::<ConnectMcpServer, McpServerToolContext<Store>>()
+}
+
+/// Add a custom MCP server to the user's connections.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ConnectMcpServer",
+ description = "Add a remote MCP server to the current user's connections by its URL, so their agents and chats can use its tools. Use when the user asks to connect, add, or install an MCP server they give you the URL of, or one whose official remote MCP URL you are sure of; never guess a URL. Most servers need the user to sign in afterwards: when the result says so, tell them to open Settings → Connections and click Connect next to the server. Its tools are available in new conversations once connected. A URL the user already has is left as it is."
+)]
+pub struct ConnectMcpServer {
+ /// The server's URL.
+ #[schemars(
+ description = "The MCP server's streamable HTTP URL, e.g. `https://mcp.linear.app/mcp`. Must be https on a public host."
+ )]
+ pub url: String,
+ /// Display name for the server.
+ #[schemars(
+ description = "Short display name for the server, e.g. `Linear`. Its tools are listed under this name."
+ )]
+ pub server_name: String,
+}
+
+impl ToolAnnotated for ConnectMcpServer {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Connect MCP server");
+}
+
+/// Response from [`ConnectMcpServer`].
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ConnectMcpServerResponse {
+ /// The server's URL.
+ pub url: String,
+ /// The server's display name.
+ pub server_name: String,
+ /// Whether the user already had this server before the call.
+ pub already_connected: bool,
+ /// Whether the server holds the user's sign-in.
+ pub authenticated: bool,
+ /// Whether the server's tools are turned on.
+ pub enabled: bool,
+ /// What happened and what the user still has to do.
+ pub summary: String,
+}
+
+#[async_trait]
+impl<Store> AsyncTool<McpServerToolContext<Store>> for ConnectMcpServer
+where
+ Store: McpServerStore,
+ anyhow::Error: From<Store::Err>,
+{
+ type Output = ConnectMcpServerResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id = %request_context.user_id, url = %self.url), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<McpServerToolContext<Store>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let servers = service_context
+ .servers
+ .as_ref()
+ .ok_or_else(|| ToolCallError {
+ description: "Connecting MCP servers is not available here.".to_owned(),
+ internal_error: anyhow::anyhow!("MCP server store not wired into this host"),
+ })?;
+ let added = servers
+ .add(
+ request_context.user_id,
+ &self.url,
+ &self.server_name,
+ AddedBy::Agent,
+ )
+ .await
+ .map_err(|error| match error {
+ AddServerError::InvalidUrl(_)
+ | AddServerError::NonPublicDestination(_)
+ | AddServerError::EmptyName => ToolCallError {
+ description: error.to_string(),
+ internal_error: anyhow::anyhow!("invalid ConnectMcpServer arguments: {error}"),
+ },
+ AddServerError::Store(error) => ToolCallError {
+ description: "Could not save the MCP server.".to_owned(),
+ internal_error: error,
+ },
+ })?;
+ Ok(ConnectMcpServerResponse::from(added))
+ }
+}
+
+impl From<AddedServer> for ConnectMcpServerResponse {
+ fn from(added: AddedServer) -> Self {
+ let already_connected = matches!(added, AddedServer::Existing(_));
+ let record = match added {
+ AddedServer::New(record) | AddedServer::Existing(record) => record,
+ };
+ let authenticated = record.credentials.is_some();
+ let name = &record.server_name;
+ let summary = match (already_connected, authenticated, record.enabled) {
+ (false, _, _) => format!(
+ "Added {name}. If it needs a sign-in, the user must open Settings → Connections and click Connect next to {name}."
+ ),
+ (true, false, _) => format!(
+ "{name} was already added but is not signed in. The user must open Settings → Connections and click Connect next to {name}."
+ ),
+ (true, true, false) => format!(
+ "{name} is already connected but turned off. The user can enable it in Settings → Connections."
+ ),
+ (true, true, true) => format!("{name} is already connected."),
+ };
+ Self {
+ url: record.url,
+ server_name: record.server_name,
+ already_connected,
+ authenticated,
+ enabled: record.enabled,
+ summary,
+ }
+ }
+}
diff --git a/crates/mcp_client/src/inbound/toolset/test.rs b/crates/mcp_client/src/inbound/toolset/test.rs
new file mode 100644
index 0000000000..f7f177336e
--- /dev/null
+++ b/crates/mcp_client/src/inbound/toolset/test.rs
@@ -0,0 +1,141 @@
+use super::*;
+use crate::domain::models::{MacroUserIdStr, McpServerRecord};
+use macro_user_id::cowlike::CowLike;
+use std::sync::{Arc, Mutex};
+
+/// In-memory [`McpServerStore`] keyed by user and URL.
+#[derive(Default)]
+struct FakeServerStore {
+ records: Mutex<Vec<McpServerRecord>>,
+}
+
+impl McpServerStore for FakeServerStore {
+ type Err = anyhow::Error;
+
+ async fn save(&self, record: &McpServerRecord) -> Result<(), Self::Err> {
+ let mut records = self.records.lock().unwrap();
+ records.retain(|stored| !(stored.user_id == record.user_id && stored.url == record.url));
+ records.push(record.clone());
+ Ok(())
+ }
+
+ async fn load(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ server_url: &str,
+ ) -> Result<Option<McpServerRecord>, Self::Err> {
+ Ok(self
+ .records
+ .lock()
+ .unwrap()
+ .iter()
+ .find(|stored| &stored.user_id == user_id && stored.url == server_url)
+ .cloned())
+ }
+
+ async fn delete(
+ &self,
+ _user_id: &MacroUserIdStr<'static>,
+ _server_url: &str,
+ ) -> Result<(), Self::Err> {
+ unimplemented!()
+ }
+
+ async fn list(
+ &self,
+ _user_id: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<McpServerRecord>, Self::Err> {
+ unimplemented!()
+ }
+}
+
+fn owner() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned()
+}
+
+#[tokio::test]
+async fn connecting_a_new_server_adds_it_for_the_caller_and_asks_them_to_sign_in() {
+ let store = Arc::new(FakeServerStore::default());
+ let context = McpServerToolContext::wired(ServerDirectory::new(store.clone()));
+
+ let response = ConnectMcpServer {
+ url: "https://mcp.linear.app/mcp".to_owned(),
+ server_name: "Linear".to_owned(),
+ }
+ .call(ServiceContext(context), RequestContext::new(owner()))
+ .await
+ .unwrap();
+
+ assert_eq!(response.url, "https://mcp.linear.app/mcp");
+ assert_eq!(response.server_name, "Linear");
+ assert!(!response.already_connected);
+ assert!(!response.authenticated);
+ assert!(response.enabled);
+ assert_eq!(
+ response.summary,
+ "Added Linear. If it needs a sign-in, the user must open Settings → Connections and click Connect next to Linear."
+ );
+ assert!(
+ store
+ .load(&owner(), "https://mcp.linear.app/mcp")
+ .await
+ .unwrap()
+ .is_some()
+ );
+}
+
+#[tokio::test]
+async fn an_invalid_url_is_reported_to_the_model() {
+ let context =
+ McpServerToolContext::wired(ServerDirectory::new(Arc::new(FakeServerStore::default())));
+
+ let error = ConnectMcpServer {
+ url: "linear".to_owned(),
+ server_name: "Linear".to_owned(),
+ }
+ .call(ServiceContext(context), RequestContext::new(owner()))
+ .await
+ .unwrap_err();
+
+ assert_eq!(error.description, "`linear` is not an http(s) URL");
+}
+
+#[tokio::test]
+async fn an_unwired_host_refuses_the_call() {
+ let context = McpServerToolContext::<FakeServerStore>::unwired();
+
+ let error = ConnectMcpServer {
+ url: "https://mcp.linear.app/mcp".to_owned(),
+ server_name: "Linear".to_owned(),
+ }
+ .call(ServiceContext(context), RequestContext::new(owner()))
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ error.description,
+ "Connecting MCP servers is not available here."
+ );
+}
+
+#[tokio::test]
+async fn a_private_destination_is_refused_and_not_stored() {
+ let store = Arc::new(FakeServerStore::default());
+ let context = McpServerToolContext::wired(ServerDirectory::new(store.clone()));
+
+ let error = ConnectMcpServer {
+ url: "https://169.254.169.254/latest/meta-data".to_owned(),
+ server_name: "Metadata".to_owned(),
+ }
+ .call(ServiceContext(context), RequestContext::new(owner()))
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ error.description,
+ "`https://169.254.169.254/latest/meta-data` is not a public https URL"
+ );
+ assert!(store.records.lock().unwrap().is_empty());
+}
diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.md
index bc9976f107..2deef9156e 100644
--- a/docs/agent-guide/ai-chat.md
+++ b/docs/agent-guide/ai-chat.md
@@ -336,6 +336,11 @@ the shimmer.
app authentication and disconnection), also available under Settings → Integrations.
Home’s **Connect your tools** and agent replies’ **Connect app** chips open this
Integrations page. It shows installed tools above the app catalog, with personal Gmail/GitHub account links in a separate section above.
+- Ask the agent to connect an MCP server by URL (for example "connect the MCP
+ server at https://mcp.example.com/mcp"). It calls **ConnectMcpServer**, which
+ adds a public `https` server to Connections and renders a **Connected MCP
+ server** card; when the server needs a sign-in, the agent asks the user to
+ click Connect next to it in Connections.
In a secondary desktop split, the new-conversation page and existing chats show
one close button beside **Show navigation** while the sidebar is collapsed.
diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.md
index 419e3ed1e3..e10c02bdd8 100644
--- a/docs/agent-guide/settings.md
+++ b/docs/agent-guide/settings.md
@@ -634,6 +634,10 @@ Provider and custom-server More menus contain Disable, Reconnect, and Disconnect
custom servers also offer Rename. Disabled grants show Enable. Unauthenticated
custom servers show Connect and Remove. Disconnect/Remove require confirmation.
Adding a custom MCP saves its name and URL; Connect on its row starts OAuth.
+In chat and agent sessions, the agent can add one for the user with the
+`ConnectMcpServer` tool: it must be a public `https` URL, the row appears here
+unauthenticated, and the user still clicks Connect to sign in. Re-adding a URL
+the user already has leaves that row and its sign-in unchanged.
The Add MCP Server dialog uses the same 24px padding above its title as on its sides.
Enabled custom servers are offered to the owner's agent sessions (Cursor, Claude,
Codex, macrod, in-memory) alongside connected apps, through the same session
diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/AddMcpServerErrors.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/AddMcpServerErrors.md
index 7cafc86875..2be6c6f237 100644
--- a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/AddMcpServerErrors.md
+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/AddMcpServerErrors.md
@@ -1,10 +1,11 @@
# Type Alias: AddMcpServerErrors
-> **AddMcpServerErrors** = \{ `401`: `string`; `500`: [`ErrorResponse`](ErrorResponse.md); \}
+> **AddMcpServerErrors** = \{ `400`: [`ErrorResponse`](ErrorResponse.md); `401`: `string`; `500`: [`ErrorResponse`](ErrorResponse.md); \}
## Properties
| Property | Type |
| ------ | ------ |
+| <a id="property-400"></a> `400` | [`ErrorResponse`](ErrorResponse.md) |
| <a id="property-401"></a> `401` | `string` |
| <a id="property-500"></a> `500` | [`ErrorResponse`](ErrorResponse.md) |
diff --git a/packages/sdk/generated/cognition/sdk.gen.ts b/packages/sdk/generated/cognition/sdk.gen.ts
index 57855fa67b..7c218cd8e9 100644
--- a/packages/sdk/generated/cognition/sdk.gen.ts
+++ b/packages/sdk/generated/cognition/sdk.gen.ts
@@ -346,7 +346,8 @@ export class Sdk extends HeyApiClient {
}
/**
- * Add a new MCP server for the authenticated user.
+ * Add a new MCP server for the authenticated user. A URL the user already
+ * has is returned as stored, keeping its credentials.
*/
public addMcpServer<ThrowOnError extends boolean = false>(options: Options<AddMcpServerData, ThrowOnError>): RequestResult<AddMcpServerResponses, AddMcpServerErrors, ThrowOnError> {
return (options.client ?? this.client).post<AddMcpServerResponses, AddMcpServerErrors, ThrowOnError>({
diff --git a/packages/sdk/generated/cognition/types.gen.ts b/packages/sdk/generated/cognition/types.gen.ts
index c958a3c0c9..e7a09319b3 100644
--- a/packages/sdk/generated/cognition/types.gen.ts
+++ b/packages/sdk/generated/cognition/types.gen.ts
@@ -2940,6 +2940,7 @@ export type AddMcpServerData = {
};
export type AddMcpServerErrors = {
+ 400: ErrorResponse;
401: string;
500: ErrorResponse;
};
diff --git a/packages/sdk/specs/cognition.json b/packages/sdk/specs/cognition.json
index c3073698b8..f04228adf9 100644
--- a/packages/sdk/specs/cognition.json
+++ b/packages/sdk/specs/cognition.json
@@ -1444,7 +1444,7 @@
},
"post": {
"tags": ["mcp"],
- "summary": "Add a new MCP server for the authenticated user.",
+ "summary": "Add a new MCP server for the authenticated user. A URL the user already\nhas is returned as stored, keeping its credentials.",
"operationId": "add_mcp_server",
"requestBody": {
"content": {
@@ -1467,6 +1467,16 @@
}
}
},
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"401": {
"description": "",
"content": {
diff --git a/services/agent_harness_service/src/cognition/api/context/test.rs b/services/agent_harness_service/src/cognition/api/context/test.rs
index 2909e32b2e..b84aaddf43 100644
--- a/services/agent_harness_service/src/cognition/api/context/test.rs
+++ b/services/agent_harness_service/src/cognition/api/context/test.rs
@@ -543,6 +543,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
forms_tool_context,
databases_sql_tool_context,
import_tool_context: ai_tools::ToolImportToolContext::unwired(),
+ mcp_server_tool_context: ai_tools::ToolMcpServerToolContext::unwired(),
chat_tool_context,
channel_tool_context: ai_tools::build_channel_tool_context_without_side_effects(
pool.clone(),
diff --git a/services/agent_harness_service/src/cognition/server.rs b/services/agent_harness_service/src/cognition/server.rs
index 287b329858..d04215ad0c 100644
--- a/services/agent_harness_service/src/cognition/server.rs
+++ b/services/agent_harness_service/src/cognition/server.rs
@@ -875,6 +875,9 @@ pub async fn build(
import_tool_context: import::inbound::toolset::ImportToolContext::wired(
import_service.clone(),
),
+ mcp_server_tool_context: ai_tools::ToolMcpServerToolContext::wired(
+ mcp_client::domain::service::ServerDirectory::new(Arc::new(mcp_server_repo.clone())),
+ ),
chat_tool_context,
channel_tool_context,
channel_media_upload_tool_context: ai_tools::build_channel_media_upload_tool_context()?,