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: per-persona Pipedream MCP server sets (#6223)

Wolf Mermelsteinf49276bd2ea1
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index f470b5619e..5d854dfc87 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -100,6 +100,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/mcp_toolset",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -212,6 +213,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/mcp_toolset",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -335,6 +337,7 @@
"crates/macro_uuid",
"crates/mcp_client",
"crates/mcp_select",
+ "crates/mcp_toolset",
"crates/memory",
"crates/mention_utils",
"crates/model",
@@ -392,6 +395,7 @@
"agent_inmem": [
"crates/activity",
"crates/agent",
+ "crates/agent_egress",
"crates/agent_fold",
"crates/agent_inmem",
"crates/agent_runtime_protocol",
@@ -433,7 +437,9 @@
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
+ "crates/fusionauth",
"crates/generic_email_domains",
+ "crates/github",
"crates/harness_id",
"crates/harness_token",
"crates/import",
@@ -461,6 +467,7 @@
"crates/macro_uuid",
"crates/mcp_client",
"crates/mcp_select",
+ "crates/mcp_toolset",
"crates/memory",
"crates/mention_utils",
"crates/model",
@@ -819,6 +826,7 @@
"crates/macro_uuid",
"crates/mcp_client",
"crates/mcp_select",
+ "crates/mcp_toolset",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -1010,6 +1018,7 @@
"crates/macro_uuid",
"crates/mcp_client",
"crates/mcp_select",
+ "crates/mcp_toolset",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -1614,6 +1623,7 @@
"crates/macro_uuid",
"crates/mcp_client",
"crates/mcp_select",
+ "crates/mcp_toolset",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -2650,6 +2660,7 @@
"crates/macro_uuid",
"crates/mcp_client",
"crates/mcp_select",
+ "crates/mcp_toolset",
"crates/memory",
"crates/mention_utils",
"crates/model",
@@ -2809,6 +2820,7 @@
"crates/macro_uuid",
"crates/mcp_client",
"crates/mcp_select",
+ "crates/mcp_toolset",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -4781,6 +4793,7 @@
"crates/macro_uuid",
"crates/mcp_client",
"crates/mcp_select",
+ "crates/mcp_toolset",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -5340,6 +5353,7 @@
"crates/macro_uuid",
"crates/mcp_client",
"crates/mcp_select",
+ "crates/mcp_toolset",
"crates/model-entity",
"crates/model-error-response",
"crates/model_file_type",
@@ -5423,6 +5437,7 @@
"crates/macro_uuid",
"crates/mcp_client",
"crates/mcp_select",
+ "crates/mcp_toolset",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -5477,6 +5492,13 @@
"services/mcp_auth_proxy",
"services/mcp_service"
],
+ "mcp_toolset": [
+ "crates/ai_toolset",
+ "crates/cowlike",
+ "crates/macro_user_id",
+ "crates/mcp_toolset",
+ "crates/workspace-hack"
+ ],
"memory": [
"crates/activity",
"crates/agent",
@@ -5547,6 +5569,7 @@
"crates/macro_uuid",
"crates/mcp_client",
"crates/mcp_select",
+ "crates/mcp_toolset",
"crates/memory",
"crates/mention_utils",
"crates/model",
@@ -6174,6 +6197,7 @@
"crates/macro_uuid",
"crates/mcp_client",
"crates/mcp_select",
+ "crates/mcp_toolset",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -6354,6 +6378,7 @@
"crates/macro_env",
"crates/macro_env_var",
"crates/macro_user_id",
+ "crates/mcp_toolset",
"crates/model-error-response",
"crates/model_user",
"crates/pipedream_mcp",
@@ -6744,6 +6769,7 @@
"crates/macro_uuid",
"crates/mcp_client",
"crates/mcp_select",
+ "crates/mcp_toolset",
"crates/memory",
"crates/mention_utils",
"crates/model",
diff --git a/.sqlx/query-1f4e3fb707254f91d431dd2b3fdb51b57ffca7a47e548309096f5b39775d1e1a.json b/.sqlx/query-1f4e3fb707254f91d431dd2b3fdb51b57ffca7a47e548309096f5b39775d1e1a.json
new file mode 100644
index 0000000000..c2a99c7da3
--- /dev/null
+++ b/.sqlx/query-1f4e3fb707254f91d431dd2b3fdb51b57ffca7a47e548309096f5b39775d1e1a.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO agent_mcp_servers (bot_id, app_slug, server_name)\n SELECT $1, slug, name\n FROM UNNEST($2::text[], $3::text[]) AS t(slug, name)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1f4e3fb707254f91d431dd2b3fdb51b57ffca7a47e548309096f5b39775d1e1a"
+}
diff --git a/.sqlx/query-4993e942985404ec388cc858815e82d08ad0185cfaa24300545f290e1ba87e49.json b/.sqlx/query-25d453dc3dd34061e52118bbede9af5a4805fee76915e1692d78b6354e5be07a.json
similarity index 71%
rename from .sqlx/query-4993e942985404ec388cc858815e82d08ad0185cfaa24300545f290e1ba87e49.json
rename to .sqlx/query-25d453dc3dd34061e52118bbede9af5a4805fee76915e1692d78b6354e5be07a.json
index bfed426c57..26aed33452 100644
--- a/.sqlx/query-4993e942985404ec388cc858815e82d08ad0185cfaa24300545f290e1ba87e49.json
+++ b/.sqlx/query-25d453dc3dd34061e52118bbede9af5a4805fee76915e1692d78b6354e5be07a.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status, status_event_name, egress_token_hash\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)\n RETURNING\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n -- A row being created cannot have an external identity yet.\n NULL::TEXT AS \"external_provider?\", NULL::TEXT AS \"external_id?\",\n NULL::TEXT AS \"external_name?\", NULL::TEXT AS \"external_url?\"\n ",
+ "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status, status_event_name, egress_token_hash,\n mcp_scope, mcp_servers\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)\n RETURNING\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n -- A row being created cannot have an external identity yet.\n NULL::TEXT AS \"external_provider?\", NULL::TEXT AS \"external_id?\",\n NULL::TEXT AS \"external_name?\", NULL::TEXT AS \"external_url?\"\n ",
"describe": {
"columns": [
{
@@ -65,51 +65,61 @@
},
{
"ordinal": 12,
- "name": "acp_session_id",
+ "name": "mcp_scope",
"type_info": "Text"
},
{
"ordinal": 13,
+ "name": "mcp_servers",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 14,
+ "name": "acp_session_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 15,
"name": "status",
"type_info": "Text"
},
{
- "ordinal": 14,
+ "ordinal": 16,
"name": "status_event_name",
"type_info": "Text"
},
{
- "ordinal": 15,
+ "ordinal": 17,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 16,
+ "ordinal": 18,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 17,
+ "ordinal": 19,
"name": "thread_channel_id?",
"type_info": "Uuid"
},
{
- "ordinal": 18,
+ "ordinal": 20,
"name": "external_provider?",
"type_info": "Text"
},
{
- "ordinal": 19,
+ "ordinal": 21,
"name": "external_id?",
"type_info": "Text"
},
{
- "ordinal": 20,
+ "ordinal": 22,
"name": "external_name?",
"type_info": "Text"
},
{
- "ordinal": 21,
+ "ordinal": 23,
"name": "external_url?",
"type_info": "Text"
}
@@ -130,7 +140,9 @@
"Text",
"Text",
"Text",
- "Text"
+ "Text",
+ "Text",
+ "Jsonb"
]
},
"nullable": [
@@ -146,6 +158,8 @@
false,
false,
true,
+ false,
+ false,
true,
false,
true,
@@ -158,5 +172,5 @@
null
]
},
- "hash": "4993e942985404ec388cc858815e82d08ad0185cfaa24300545f290e1ba87e49"
+ "hash": "25d453dc3dd34061e52118bbede9af5a4805fee76915e1692d78b6354e5be07a"
}
diff --git a/.sqlx/query-e110350d84019c5f95862604b525421b8aeffae90f0e6852cc76bb753e9d3e6d.json b/.sqlx/query-2757506f01322f58baeea71fb6779b867143be6312ef20a1bfd51e0f0dcd974d.json
similarity index 72%
rename from .sqlx/query-e110350d84019c5f95862604b525421b8aeffae90f0e6852cc76bb753e9d3e6d.json
rename to .sqlx/query-2757506f01322f58baeea71fb6779b867143be6312ef20a1bfd51e0f0dcd974d.json
index d86b878230..1e7244b7a1 100644
--- a/.sqlx/query-e110350d84019c5f95862604b525421b8aeffae90f0e6852cc76bb753e9d3e6d.json
+++ b/.sqlx/query-2757506f01322f58baeea71fb6779b867143be6312ef20a1bfd51e0f0dcd974d.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE id = $1\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY agent_session.created_at DESC\n LIMIT 1\n ",
"describe": {
"columns": [
{
@@ -65,57 +65,68 @@
},
{
"ordinal": 12,
- "name": "acp_session_id",
+ "name": "mcp_scope",
"type_info": "Text"
},
{
"ordinal": 13,
+ "name": "mcp_servers",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 14,
+ "name": "acp_session_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 15,
"name": "status",
"type_info": "Text"
},
{
- "ordinal": 14,
+ "ordinal": 16,
"name": "status_event_name",
"type_info": "Text"
},
{
- "ordinal": 15,
+ "ordinal": 17,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 16,
+ "ordinal": 18,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 17,
+ "ordinal": 19,
"name": "thread_channel_id?",
"type_info": "Uuid"
},
{
- "ordinal": 18,
+ "ordinal": 20,
"name": "external_provider?",
"type_info": "Text"
},
{
- "ordinal": 19,
+ "ordinal": 21,
"name": "external_id?",
"type_info": "Text"
},
{
- "ordinal": 20,
+ "ordinal": 22,
"name": "external_name?",
"type_info": "Text"
},
{
- "ordinal": 21,
+ "ordinal": 23,
"name": "external_url?",
"type_info": "Text"
}
],
"parameters": {
"Left": [
+ "Uuid",
"Uuid"
]
},
@@ -132,6 +143,8 @@
false,
false,
true,
+ false,
+ false,
true,
false,
true,
@@ -144,5 +157,5 @@
true
]
},
- "hash": "e110350d84019c5f95862604b525421b8aeffae90f0e6852cc76bb753e9d3e6d"
+ "hash": "2757506f01322f58baeea71fb6779b867143be6312ef20a1bfd51e0f0dcd974d"
}
diff --git a/.sqlx/query-e975e75d2da18b8206df0dc5d4369bea0bc62546e28bcdcecb89ef04fa083f9c.json b/.sqlx/query-51442f5d740386b1d930feba1450f46991917be4d87a9774105daa1c245bd458.json
similarity index 74%
rename from .sqlx/query-e975e75d2da18b8206df0dc5d4369bea0bc62546e28bcdcecb89ef04fa083f9c.json
rename to .sqlx/query-51442f5d740386b1d930feba1450f46991917be4d87a9774105daa1c245bd458.json
index d2e517995a..b352a54dc2 100644
--- a/.sqlx/query-e975e75d2da18b8206df0dc5d4369bea0bc62546e28bcdcecb89ef04fa083f9c.json
+++ b/.sqlx/query-51442f5d740386b1d930feba1450f46991917be4d87a9774105daa1c245bd458.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE egress_token_hash = $1\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE egress_token_hash = $1\n ",
"describe": {
"columns": [
{
@@ -65,51 +65,61 @@
},
{
"ordinal": 12,
- "name": "acp_session_id",
+ "name": "mcp_scope",
"type_info": "Text"
},
{
"ordinal": 13,
+ "name": "mcp_servers",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 14,
+ "name": "acp_session_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 15,
"name": "status",
"type_info": "Text"
},
{
- "ordinal": 14,
+ "ordinal": 16,
"name": "status_event_name",
"type_info": "Text"
},
{
- "ordinal": 15,
+ "ordinal": 17,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 16,
+ "ordinal": 18,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 17,
+ "ordinal": 19,
"name": "thread_channel_id?",
"type_info": "Uuid"
},
{
- "ordinal": 18,
+ "ordinal": 20,
"name": "external_provider?",
"type_info": "Text"
},
{
- "ordinal": 19,
+ "ordinal": 21,
"name": "external_id?",
"type_info": "Text"
},
{
- "ordinal": 20,
+ "ordinal": 22,
"name": "external_name?",
"type_info": "Text"
},
{
- "ordinal": 21,
+ "ordinal": 23,
"name": "external_url?",
"type_info": "Text"
}
@@ -132,6 +142,8 @@
false,
false,
true,
+ false,
+ false,
true,
false,
true,
@@ -144,5 +156,5 @@
true
]
},
- "hash": "e975e75d2da18b8206df0dc5d4369bea0bc62546e28bcdcecb89ef04fa083f9c"
+ "hash": "51442f5d740386b1d930feba1450f46991917be4d87a9774105daa1c245bd458"
}
diff --git a/.sqlx/query-76c662c3c7b23512dfa8a466c1e1fa4f03306e93e17003876ceab7081a88ef76.json b/.sqlx/query-52e3880dea11a6285fa0586f87ddd3e2141389f037166868942708cc8c70999a.json
similarity index 64%
rename from .sqlx/query-76c662c3c7b23512dfa8a466c1e1fa4f03306e93e17003876ceab7081a88ef76.json
rename to .sqlx/query-52e3880dea11a6285fa0586f87ddd3e2141389f037166868942708cc8c70999a.json
index a14ea9e6aa..baace6bdcc 100644
--- a/.sqlx/query-76c662c3c7b23512dfa8a466c1e1fa4f03306e93e17003876ceab7081a88ef76.json
+++ b/.sqlx/query-52e3880dea11a6285fa0586f87ddd3e2141389f037166868942708cc8c70999a.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO agent_configs (\n bot_id, instructions, harness, harness_id, default_model, channel_scope\n )\n VALUES ($1, $2, $3, $4, $5, $6)\n ",
+ "query": "\n INSERT INTO agent_configs (\n bot_id, instructions, harness, harness_id, default_model, channel_scope, mcp_scope\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ",
"describe": {
"columns": [],
"parameters": {
@@ -10,10 +10,11 @@
"Text",
"Uuid",
"Text",
+ "Text",
"Text"
]
},
"nullable": []
},
- "hash": "76c662c3c7b23512dfa8a466c1e1fa4f03306e93e17003876ceab7081a88ef76"
+ "hash": "52e3880dea11a6285fa0586f87ddd3e2141389f037166868942708cc8c70999a"
}
diff --git a/.sqlx/query-2193da6edede173e322e1f6f7ca1206ea8523c16b99d723be67afaa56c7075ec.json b/.sqlx/query-5ef0fcf615784b75dbd205d642053f5b565c8d2ae1e86a2ee92f99cc32065c1e.json
similarity index 64%
rename from .sqlx/query-2193da6edede173e322e1f6f7ca1206ea8523c16b99d723be67afaa56c7075ec.json
rename to .sqlx/query-5ef0fcf615784b75dbd205d642053f5b565c8d2ae1e86a2ee92f99cc32065c1e.json
index 9e290f05bc..49fee08730 100644
--- a/.sqlx/query-2193da6edede173e322e1f6f7ca1206ea8523c16b99d723be67afaa56c7075ec.json
+++ b/.sqlx/query-5ef0fcf615784b75dbd205d642053f5b565c8d2ae1e86a2ee92f99cc32065c1e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE agent_configs\n SET instructions = $2,\n harness = $3,\n harness_id = $4,\n default_model = $5,\n channel_scope = $6,\n updated_at = now()\n WHERE bot_id = $1\n ",
+ "query": "\n UPDATE agent_configs\n SET instructions = $2,\n harness = $3,\n harness_id = $4,\n default_model = $5,\n channel_scope = $6,\n mcp_scope = $7,\n updated_at = now()\n WHERE bot_id = $1\n ",
"describe": {
"columns": [],
"parameters": {
@@ -10,10 +10,11 @@
"Text",
"Uuid",
"Text",
+ "Text",
"Text"
]
},
"nullable": []
},
- "hash": "2193da6edede173e322e1f6f7ca1206ea8523c16b99d723be67afaa56c7075ec"
+ "hash": "5ef0fcf615784b75dbd205d642053f5b565c8d2ae1e86a2ee92f99cc32065c1e"
}
diff --git a/.sqlx/query-0057301723d11cedc003eab4fb1355b7352cd9a137f0e8807c802e88f538c7ee.json b/.sqlx/query-797e496988921e2f577b148abb390ab5bd246eea93626be6103ccd5849ec6c98.json
similarity index 68%
rename from .sqlx/query-0057301723d11cedc003eab4fb1355b7352cd9a137f0e8807c802e88f538c7ee.json
rename to .sqlx/query-797e496988921e2f577b148abb390ab5bd246eea93626be6103ccd5849ec6c98.json
index b57820aaac..359dfc92bc 100644
--- a/.sqlx/query-0057301723d11cedc003eab4fb1355b7352cd9a137f0e8807c802e88f538c7ee.json
+++ b/.sqlx/query-797e496988921e2f577b148abb390ab5bd246eea93626be6103ccd5849ec6c98.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.kind = 'owned'\n AND b.deleted_at IS NULL\n AND (\n b.owner_user_id = $1\n OR b.team_id IN (\n SELECT team_id FROM team_user WHERE user_id = $1\n )\n )\n ORDER BY b.created_at ASC, b.id ASC\n ",
+ "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\",\n a.mcp_scope,\n ARRAY(\n SELECT m.app_slug\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_app_slugs!\",\n ARRAY(\n SELECT m.server_name\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_server_names!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.kind = 'owned'\n AND b.deleted_at IS NULL\n AND (\n b.owner_user_id = $1\n OR b.team_id IN (\n SELECT team_id FROM team_user WHERE user_id = $1\n )\n )\n ORDER BY b.created_at ASC, b.id ASC\n ",
"describe": {
"columns": [
{
@@ -97,6 +97,21 @@
"ordinal": 18,
"name": "channel_ids!",
"type_info": "UuidArray"
+ },
+ {
+ "ordinal": 19,
+ "name": "mcp_scope",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 20,
+ "name": "mcp_app_slugs!",
+ "type_info": "TextArray"
+ },
+ {
+ "ordinal": 21,
+ "name": "mcp_server_names!",
+ "type_info": "TextArray"
}
],
"parameters": {
@@ -123,8 +138,11 @@
true,
false,
false,
+ null,
+ false,
+ null,
null
]
},
- "hash": "0057301723d11cedc003eab4fb1355b7352cd9a137f0e8807c802e88f538c7ee"
+ "hash": "797e496988921e2f577b148abb390ab5bd246eea93626be6103ccd5849ec6c98"
}
diff --git a/.sqlx/query-5a3dd1831370d60a05f9cda9a1a8608daa8c7fe4f252320f6f3224517dc9019a.json b/.sqlx/query-7de3b94415bb892f1005f5090865337decd1a2a106f161b42ba4dd208e5e97e9.json
similarity index 74%
rename from .sqlx/query-5a3dd1831370d60a05f9cda9a1a8608daa8c7fe4f252320f6f3224517dc9019a.json
rename to .sqlx/query-7de3b94415bb892f1005f5090865337decd1a2a106f161b42ba4dd208e5e97e9.json
index 77a1a2927d..2d6b1e7b1b 100644
--- a/.sqlx/query-5a3dd1831370d60a05f9cda9a1a8608daa8c7fe4f252320f6f3224517dc9019a.json
+++ b/.sqlx/query-7de3b94415bb892f1005f5090865337decd1a2a106f161b42ba4dd208e5e97e9.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY agent_session.created_at DESC\n LIMIT 1\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE id = $1\n ",
"describe": {
"columns": [
{
@@ -65,58 +65,67 @@
},
{
"ordinal": 12,
- "name": "acp_session_id",
+ "name": "mcp_scope",
"type_info": "Text"
},
{
"ordinal": 13,
+ "name": "mcp_servers",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 14,
+ "name": "acp_session_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 15,
"name": "status",
"type_info": "Text"
},
{
- "ordinal": 14,
+ "ordinal": 16,
"name": "status_event_name",
"type_info": "Text"
},
{
- "ordinal": 15,
+ "ordinal": 17,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 16,
+ "ordinal": 18,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 17,
+ "ordinal": 19,
"name": "thread_channel_id?",
"type_info": "Uuid"
},
{
- "ordinal": 18,
+ "ordinal": 20,
"name": "external_provider?",
"type_info": "Text"
},
{
- "ordinal": 19,
+ "ordinal": 21,
"name": "external_id?",
"type_info": "Text"
},
{
- "ordinal": 20,
+ "ordinal": 22,
"name": "external_name?",
"type_info": "Text"
},
{
- "ordinal": 21,
+ "ordinal": 23,
"name": "external_url?",
"type_info": "Text"
}
],
"parameters": {
"Left": [
- "Uuid",
"Uuid"
]
},
@@ -133,6 +142,8 @@
false,
false,
true,
+ false,
+ false,
true,
false,
true,
@@ -145,5 +156,5 @@
true
]
},
- "hash": "5a3dd1831370d60a05f9cda9a1a8608daa8c7fe4f252320f6f3224517dc9019a"
+ "hash": "7de3b94415bb892f1005f5090865337decd1a2a106f161b42ba4dd208e5e97e9"
}
diff --git a/.sqlx/query-39d74321afaaed143e3462074610e033ce0c07edbb1744bf012fc6ca9534b209.json b/.sqlx/query-a1685ed15d4c123c062b9a4d41170336cf5fbac50ad448e1451d4b40a5ba6080.json
similarity index 72%
rename from .sqlx/query-39d74321afaaed143e3462074610e033ce0c07edbb1744bf012fc6ca9534b209.json
rename to .sqlx/query-a1685ed15d4c123c062b9a4d41170336cf5fbac50ad448e1451d4b40a5ba6080.json
index bee02f81d6..2227387659 100644
--- a/.sqlx/query-39d74321afaaed143e3462074610e033ce0c07edbb1744bf012fc6ca9534b209.json
+++ b/.sqlx/query-a1685ed15d4c123c062b9a4d41170336cf5fbac50ad448e1451d4b40a5ba6080.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.id = $1\n AND b.kind = 'owned'\n AND b.deleted_at IS NULL\n ",
+ "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\",\n a.mcp_scope,\n ARRAY(\n SELECT m.app_slug\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_app_slugs!\",\n ARRAY(\n SELECT m.server_name\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_server_names!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.id = $1\n AND b.kind = 'owned'\n AND b.deleted_at IS NULL\n ",
"describe": {
"columns": [
{
@@ -97,6 +97,21 @@
"ordinal": 18,
"name": "channel_ids!",
"type_info": "UuidArray"
+ },
+ {
+ "ordinal": 19,
+ "name": "mcp_scope",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 20,
+ "name": "mcp_app_slugs!",
+ "type_info": "TextArray"
+ },
+ {
+ "ordinal": 21,
+ "name": "mcp_server_names!",
+ "type_info": "TextArray"
}
],
"parameters": {
@@ -123,8 +138,11 @@
true,
false,
false,
+ null,
+ false,
+ null,
null
]
},
- "hash": "39d74321afaaed143e3462074610e033ce0c07edbb1744bf012fc6ca9534b209"
+ "hash": "a1685ed15d4c123c062b9a4d41170336cf5fbac50ad448e1451d4b40a5ba6080"
}
diff --git a/.sqlx/query-157e3c11a5b3d87c3a6be9c39ccb6d105b569db6d68f2154b97dbd3c129187ca.json b/.sqlx/query-a82f6bfedc84f43370145bf86222f10d1d83e53f5413f1c4fafcd122f052a2c0.json
similarity index 73%
rename from .sqlx/query-157e3c11a5b3d87c3a6be9c39ccb6d105b569db6d68f2154b97dbd3c129187ca.json
rename to .sqlx/query-a82f6bfedc84f43370145bf86222f10d1d83e53f5413f1c4fafcd122f052a2c0.json
index 0ccbefde62..73d614e9f5 100644
--- a/.sqlx/query-157e3c11a5b3d87c3a6be9c39ccb6d105b569db6d68f2154b97dbd3c129187ca.json
+++ b/.sqlx/query-a82f6bfedc84f43370145bf86222f10d1d83e53f5413f1c4fafcd122f052a2c0.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1\n ORDER BY agent_session.created_at DESC\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1\n ORDER BY agent_session.created_at DESC\n ",
"describe": {
"columns": [
{
@@ -65,51 +65,61 @@
},
{
"ordinal": 12,
- "name": "acp_session_id",
+ "name": "mcp_scope",
"type_info": "Text"
},
{
"ordinal": 13,
+ "name": "mcp_servers",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 14,
+ "name": "acp_session_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 15,
"name": "status",
"type_info": "Text"
},
{
- "ordinal": 14,
+ "ordinal": 16,
"name": "status_event_name",
"type_info": "Text"
},
{
- "ordinal": 15,
+ "ordinal": 17,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 16,
+ "ordinal": 18,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 17,
+ "ordinal": 19,
"name": "thread_channel_id?",
"type_info": "Uuid"
},
{
- "ordinal": 18,
+ "ordinal": 20,
"name": "external_provider?",
"type_info": "Text"
},
{
- "ordinal": 19,
+ "ordinal": 21,
"name": "external_id?",
"type_info": "Text"
},
{
- "ordinal": 20,
+ "ordinal": 22,
"name": "external_name?",
"type_info": "Text"
},
{
- "ordinal": 21,
+ "ordinal": 23,
"name": "external_url?",
"type_info": "Text"
}
@@ -132,6 +142,8 @@
false,
false,
true,
+ false,
+ false,
true,
false,
true,
@@ -144,5 +156,5 @@
true
]
},
- "hash": "157e3c11a5b3d87c3a6be9c39ccb6d105b569db6d68f2154b97dbd3c129187ca"
+ "hash": "a82f6bfedc84f43370145bf86222f10d1d83e53f5413f1c4fafcd122f052a2c0"
}
diff --git a/.sqlx/query-fc8d57060dd698bb2634cfcb7fa43bb49ac44b982dce713b3631cf866a4c0d6e.json b/.sqlx/query-fc8d57060dd698bb2634cfcb7fa43bb49ac44b982dce713b3631cf866a4c0d6e.json
new file mode 100644
index 0000000000..be4a3e40c6
--- /dev/null
+++ b/.sqlx/query-fc8d57060dd698bb2634cfcb7fa43bb49ac44b982dce713b3631cf866a4c0d6e.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM agent_mcp_servers WHERE bot_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "fc8d57060dd698bb2634cfcb7fa43bb49ac44b982dce713b3631cf866a4c0d6e"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 56277b63d6..77684958f0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -356,6 +356,7 @@ version = "0.1.0"
dependencies = [
"agent",
"agent-client-protocol",
+ "agent_egress",
"agent_fold",
"agent_runtime_protocol",
"agent_session",
@@ -363,19 +364,28 @@ dependencies = [
"ai_toolset",
"ai_usage",
"bot_id",
+ "bytes",
"dashmap",
"futures",
+ "http 1.4.0",
+ "http-body-util",
"macro_user_id",
"macro_uuid",
+ "mcp_select",
+ "mcp_toolset",
"memory",
"prompt",
"rig-agent",
+ "rmcp",
"serde",
"serde_json",
"sqlx",
+ "sse-stream",
+ "thiserror 2.0.18",
"tokio",
"tokio-util",
"tracing",
+ "url",
"workspace-hack",
]
@@ -10272,6 +10282,22 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "mcp_toolset"
+version = "0.1.0"
+dependencies = [
+ "ai_toolset",
+ "anyhow",
+ "futures",
+ "regex",
+ "rmcp",
+ "schemars 1.2.1",
+ "serde_json",
+ "thiserror 2.0.18",
+ "tracing",
+ "workspace-hack",
+]
+
[[package]]
name = "md-5"
version = "0.10.6"
@@ -12378,8 +12404,8 @@ dependencies = [
"futures",
"macro_authorization",
"macro_user_id",
+ "mcp_toolset",
"model-error-response",
- "regex",
"reqwest 0.13.4",
"rmcp",
"schemars 1.2.1",
diff --git a/Cargo.toml b/Cargo.toml
index 0b64a9362c..58698c7db5 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -61,6 +61,7 @@ members = [
"crates/maybe_send",
"crates/memory",
"crates/mcp_select",
+ "crates/mcp_toolset",
"crates/pipedream_mcp",
"crates/onboarding",
"crates/predicate_index",
@@ -265,6 +266,7 @@ reqwest = { version = "0.13", default-features = false, features = [
"rustls",
] }
rmcp = "1.6.0"
+sse-stream = "0.2"
rootcause = { version = "0.12", features = ["compat-anyhow1"] }
rustls = { version = "0.23", default-features = false, features = ["aws_lc_rs"] }
rootcause-tracing = "0.12.1"
diff --git a/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts b/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts
index 46ae8fc4d7..3fa4af7bfd 100644
--- a/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts
+++ b/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts
@@ -31,6 +31,7 @@ function agent(
default_model: 'model',
harness,
instructions: '',
+ mcp: { scope: 'owner_connections' },
};
}
diff --git a/apps/web/src/features/settings/Agents.test.tsx b/apps/web/src/features/settings/Agents.test.tsx
index 57455963bd..60a01d161a 100644
--- a/apps/web/src/features/settings/Agents.test.tsx
+++ b/apps/web/src/features/settings/Agents.test.tsx
@@ -105,6 +105,60 @@ vi.mock('@core/context/channels', () => ({
}),
}));
+const pipedreamMocks = vi.hoisted(() => ({
+ enabled: true,
+ connected: [] as string[],
+ connect: vi.fn(),
+ catalog: [
+ {
+ app_slug: 'linear',
+ display_name: 'Linear',
+ description: 'Issue tracking',
+ icon_url: null,
+ },
+ {
+ app_slug: 'notion',
+ display_name: 'Notion',
+ description: 'Docs and wikis',
+ icon_url: null,
+ },
+ ],
+}));
+
+vi.mock('@core/pipedream/flag', () => ({
+ usePipedreamMcpFlag: () => () => pipedreamMocks.enabled,
+}));
+
+vi.mock('@queries/pipedream-connectors', () => ({
+ usePipedreamConnectedSlugs: () => ({
+ slugs: () => new Set(pipedreamMocks.connected),
+ ready: () => true,
+ }),
+ usePipedreamCatalogQuery: (search: () => string) => ({
+ get data() {
+ const term = search().trim().toLowerCase();
+ return {
+ pages: [
+ {
+ servers: pipedreamMocks.catalog.filter((entry) =>
+ entry.display_name.toLowerCase().includes(term)
+ ),
+ next_cursor: null,
+ },
+ ],
+ pageParams: [undefined],
+ };
+ },
+ isFetching: false,
+ isFetchingNextPage: false,
+ hasNextPage: false,
+ isError: false,
+ fetchNextPage: vi.fn(),
+ refetch: vi.fn(),
+ }),
+ connectPipedreamApp: pipedreamMocks.connect,
+}));
+
beforeAll(() => {
vi.stubGlobal('scrollTo', vi.fn());
});
@@ -123,6 +177,15 @@ beforeEach(() => {
agentMocks.currentTeam = { team: { id: 'team-1' } };
agentMocks.isTeamOwner = false;
harnessMocks.query.data = [];
+ pipedreamMocks.enabled = true;
+ pipedreamMocks.connected = [];
+ pipedreamMocks.connect.mockReset();
+ pipedreamMocks.connect.mockImplementation(
+ async (args: { appSlug: string }) => {
+ pipedreamMocks.connected = [...pipedreamMocks.connected, args.appSlug];
+ return 'connected';
+ }
+ );
});
const MACROD_HARNESS = {
@@ -286,6 +349,7 @@ describe('Agents', () => {
harness: 'in-memory',
name: 'Bug resolver',
instructions: 'Fix the root cause.',
+ mcp: { scope: 'owner_connections' },
teamId: undefined,
});
expect(agentMocks.toastSuccess).toHaveBeenCalledWith('Agent updated');
@@ -507,6 +571,7 @@ describe('Agents', () => {
harness: 'in-memory',
name: 'Bug fixer',
instructions: 'Fix the root cause and add tests.',
+ mcp: { scope: 'owner_connections' },
teamId: 'team-1',
});
expect(agentMocks.toastSuccess).toHaveBeenCalledWith('Agent created');
@@ -594,6 +659,7 @@ describe('Agents', () => {
harnessId: MACROD_HARNESS.id,
name: 'Bug fixer',
instructions: '',
+ mcp: { scope: 'owner_connections' },
teamId: undefined,
});
});
@@ -635,4 +701,170 @@ describe('Agents', () => {
expect(defaultModel.tagName).toBe('INPUT');
expect(defaultModel).toHaveProperty('value', 'default');
});
+
+ const linearAgent = {
+ bot: {
+ id: 'agent-mcp',
+ kind: 'owned',
+ owner: { type: 'team', team_id: 'team-1' },
+ name: 'Triage bot',
+ handle: 'triage-bot',
+ has_agent: true,
+ created_by: 'macro|[email protected]',
+ created_at: '2026-08-27T12:00:00Z',
+ updated_at: '2026-08-27T12:00:00Z',
+ },
+ instructions: '',
+ harness: 'in-memory',
+ default_model: Model.sonnet5,
+ channel_scope: 'all',
+ channel_ids: [],
+ mcp: {
+ scope: 'selected',
+ servers: [
+ { app_slug: 'linear', server_name: 'Linear' },
+ { app_slug: 'notion', server_name: 'Notion' },
+ ],
+ },
+ };
+
+ it('hides the Connections section when the Pipedream stack is off but keeps the selection', async () => {
+ pipedreamMocks.enabled = false;
+ agentMocks.query.data = [linearAgent];
+ render(() => <Agents />);
+ fireEvent.click(screen.getByRole('button', { name: 'Edit Triage bot' }));
+
+ const dialog = screen.getByRole('dialog');
+ expect(within(dialog).queryByText('Connections')).toBeNull();
+ fireEvent.click(
+ within(dialog).getByRole('button', { name: 'Save changes' })
+ );
+
+ await waitFor(() => {
+ expect(agentMocks.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ mcp: { scope: 'selected', servers: linearAgent.mcp.servers },
+ })
+ );
+ });
+ });
+
+ it('defaults new agents to the owner connections policy', () => {
+ render(() => <Agents />);
+ fireEvent.click(screen.getByRole('button', { name: 'Create agent' }));
+
+ const dialog = screen.getByRole('dialog');
+ expect(
+ within(dialog).getByLabelText('Use my connected apps')
+ ).toHaveProperty('checked', true);
+ expect(within(dialog).queryByLabelText('Search connectors')).toBeNull();
+ });
+
+ it('picks apps from the whole catalog, shows the viewer connection state, and persists them', async () => {
+ render(() => <Agents />);
+ fireEvent.click(screen.getByRole('button', { name: 'Create agent' }));
+
+ const dialog = screen.getByRole('dialog');
+ fireEvent.input(within(dialog).getByLabelText('Name'), {
+ target: { value: 'Triage bot' },
+ });
+ fireEvent.click(within(dialog).getByLabelText('Specific apps'));
+
+ // An explicit selection with nothing in it is not something to save.
+ expect(
+ within(dialog).getByRole('button', { name: 'Create agent' })
+ ).toHaveProperty('disabled', true);
+
+ fireEvent.input(within(dialog).getByLabelText('Search connectors'), {
+ target: { value: 'lin' },
+ });
+ await waitFor(() => {
+ expect(
+ within(dialog).getByRole('option', { name: /Linear/ })
+ ).toBeTruthy();
+ });
+ fireEvent.click(within(dialog).getByRole('option', { name: /Linear/ }));
+
+ // The pick is listed as not connected for this viewer, with a way in.
+ await waitFor(() => {
+ expect(within(dialog).getByText('Linear')).toBeTruthy();
+ });
+ expect(within(dialog).getByLabelText('Not connected')).toBeTruthy();
+ expect(
+ within(dialog).getByRole('button', { name: 'Connect' })
+ ).toBeTruthy();
+ // ...and no longer offered by the search.
+ fireEvent.input(within(dialog).getByLabelText('Search connectors'), {
+ target: { value: 'lin' },
+ });
+ await waitFor(() => {
+ expect(
+ within(dialog).queryByRole('option', { name: /Linear/ })
+ ).toBeNull();
+ });
+
+ // Unconnected picks never block saving: the agent's author chooses the
+ // apps, each person connects their own.
+ fireEvent.click(
+ within(dialog).getByRole('button', { name: 'Create agent' })
+ );
+ await waitFor(() => {
+ expect(agentMocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ mcp: {
+ scope: 'selected',
+ servers: [{ app_slug: 'linear', server_name: 'Linear' }],
+ },
+ })
+ );
+ });
+ });
+
+ it('connects a picked app in place and flips its indicator without saving', async () => {
+ agentMocks.update.mockClear();
+ agentMocks.query.data = [linearAgent];
+ render(() => <Agents />);
+ fireEvent.click(screen.getByRole('button', { name: 'Edit Triage bot' }));
+
+ const dialog = screen.getByRole('dialog');
+ expect(within(dialog).getByLabelText('Specific apps')).toHaveProperty(
+ 'checked',
+ true
+ );
+ expect(within(dialog).getAllByLabelText('Not connected')).toHaveLength(2);
+ // Team agents say out loud that connections are per person.
+ expect(within(dialog).getByText(/Connections are personal/)).toBeTruthy();
+
+ // Linear is listed first; its row carries the first Connect action.
+ fireEvent.click(
+ within(dialog).getAllByRole('button', {
+ name: 'Connect',
+ })[0] as HTMLElement
+ );
+
+ await waitFor(() => {
+ expect(pipedreamMocks.connect).toHaveBeenCalledWith(
+ expect.objectContaining({ appSlug: 'linear', serverName: 'Linear' })
+ );
+ });
+ expect(agentMocks.update).not.toHaveBeenCalled();
+
+ // Removing one pick keeps the other.
+ fireEvent.click(
+ within(dialog).getByRole('button', { name: 'Remove Notion' })
+ );
+ fireEvent.click(
+ within(dialog).getByRole('button', { name: 'Save changes' })
+ );
+ await waitFor(() => {
+ expect(agentMocks.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ mcp: {
+ scope: 'selected',
+ servers: [{ app_slug: 'linear', server_name: 'Linear' }],
+ },
+ })
+ );
+ });
+ });
});
diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsx
index ea997e2a30..ac46a9608d 100644
--- a/apps/web/src/features/settings/Agents.tsx
+++ b/apps/web/src/features/settings/Agents.tsx
@@ -5,6 +5,7 @@ import { toast } from '@core/component/Toast/Toast';
import { MACRO_AGENT_BOT_ID } from '@core/constant/macroAgent';
import { useChannelsContext } from '@core/context/channels';
import { useUserId } from '@core/context/user';
+import { usePipedreamMcpFlag } from '@core/pipedream/flag';
import MacroLogo from '@icon/macro-logo.svg';
import PencilIcon from '@phosphor/pencil-simple.svg';
import PlusIcon from '@phosphor/plus.svg';
@@ -25,12 +26,16 @@ import {
useCursorModelsQuery,
} from '@queries/auth/cursor-api-key';
import { useHarnessesQuery } from '@queries/harnesses/harnesses';
+import { usePipedreamConnectedSlugs } from '@queries/pipedream-connectors';
import { useCurrentTeamQuery, useIsTeamOwner } from '@queries/team/teams';
+import type { AgentMcpServer } from '@service-storage/generated/schemas/agentMcpServer';
+import type { AgentMcpServers } from '@service-storage/generated/schemas/agentMcpServers';
import { Avatar, Button, Dialog, Panel } from '@ui';
import { createMemo, createSignal, For, Show } from 'solid-js';
import { botAssignableChannelOptions } from '../channel/Bots/botChannelOptions';
import { canDeleteBot } from '../channel/Bots/botPermissions';
import { ChannelMultiSelect } from '../channel/Bots/ChannelMultiSelect';
+import { PipedreamAppPicker } from './PipedreamAppPicker';
import {
ChoiceRow,
SettingsCard,
@@ -547,7 +552,32 @@ function AgentDialog(props: {
const [share, setShare] = createSignal<AgentShare>(
props.agent?.bot.owner?.type === 'team' ? 'Team' : 'Private'
);
+ const pipedreamMcp = usePipedreamMcpFlag();
+ const connections = usePipedreamConnectedSlugs();
+ const [mcp, setMcp] = createSignal<AgentMcpServers>(
+ props.agent?.mcp ?? { scope: 'owner_connections' }
+ );
+ const selectedMcpServers = (): AgentMcpServer[] => {
+ const current = mcp();
+ return current.scope === 'selected' ? current.servers : [];
+ };
+ // Picks survive a round trip through "Use my connected apps", so toggling
+ // the radio to compare does not throw the list away.
+ let rememberedMcpServers: AgentMcpServer[] = selectedMcpServers();
+ const setMcpScope = (scope: AgentMcpServers['scope']) => {
+ if (scope === 'selected') {
+ setMcp({ scope: 'selected', servers: rememberedMcpServers });
+ } else {
+ rememberedMcpServers = selectedMcpServers();
+ setMcp({ scope: 'owner_connections' });
+ }
+ };
+ const setSelectedMcpServers = (servers: AgentMcpServer[]) => {
+ rememberedMcpServers = servers;
+ setMcp({ scope: 'selected', servers });
+ };
let avatarInputRef: HTMLInputElement | undefined;
+ let dialogContentRef: HTMLDivElement | undefined;
const close = () => props.onClose();
@@ -581,6 +611,7 @@ function AgentDialog(props: {
selectedHarness() !== undefined &&
selectedDefaultModelId().length > 0 &&
(channelMode() === 'all' || selectedChannelIds().length > 0) &&
+ (mcp().scope === 'owner_connections' || selectedMcpServers().length > 0) &&
(share() === 'Private' ? props.canMakePrivate : props.canShareWithTeam);
const selectedTeamId = () => {
@@ -607,6 +638,9 @@ function AgentDialog(props: {
harnessId: harness?.kind === 'macrod' ? harness.id : undefined,
name: name().trim(),
instructions: instructions().trim(),
+ // Always sent, flag or no flag, so an editor without the Connections
+ // section never wipes a selection somebody else made.
+ mcp: mcp(),
teamId: selectedTeamId(),
});
if (saved) close();
@@ -619,6 +653,9 @@ function AgentDialog(props: {
position="center"
visibleScrim
class="w-[min(720px,calc(100vw-16px))]"
+ contentRef={(element) => {
+ dialogContentRef = element;
+ }}
>
<Panel depth={2} class="max-h-[88vh] rounded-xl text-ink">
<Panel.Header class="justify-between px-3">
@@ -824,6 +861,53 @@ function AgentDialog(props: {
</div>
</AgentFormSection>
+ <Show when={pipedreamMcp()}>
+ <AgentFormSection
+ title="Connections"
+ description="Which connected apps (MCP tools) this agent can use."
+ >
+ <fieldset class="flex flex-col gap-2">
+ <legend class="sr-only">Connections</legend>
+ <ChoiceRow
+ name="agent-mcp-mode"
+ value="owner_connections"
+ checked={mcp().scope === 'owner_connections'}
+ title="Use my connected apps"
+ description="The agent uses whatever apps the person running it has connected."
+ onChange={() => setMcpScope('owner_connections')}
+ />
+ <ChoiceRow
+ name="agent-mcp-mode"
+ value="selected"
+ checked={mcp().scope === 'selected'}
+ title="Specific apps"
+ description="Pick apps from the catalog. Each person connects their own account."
+ onChange={() => setMcpScope('selected')}
+ />
+ </fieldset>
+
+ <Show when={mcp().scope === 'selected'}>
+ <div class="mt-3 border-t border-edge-muted pt-3">
+ <PipedreamAppPicker
+ selected={selectedMcpServers()}
+ onChange={setSelectedMcpServers}
+ connectedSlugs={connections.slugs}
+ connectionsReady={connections.ready}
+ connectContainer={() => dialogContentRef}
+ />
+ </div>
+ </Show>
+
+ <Show when={share() === 'Team'}>
+ <p class="mt-3 border-t border-edge-muted pt-3 text-xs text-ink-extra-muted">
+ Connections are personal. Teammates who use this agent
+ connect these apps under Settings → Connections; the
+ indicators here show only your own.
+ </p>
+ </Show>
+ </AgentFormSection>
+ </Show>
+
<AgentFormSection
title="Channels"
description="Choose whether this agent is global or channel-specific."
diff --git a/apps/web/src/features/settings/PipedreamAppPicker.tsx b/apps/web/src/features/settings/PipedreamAppPicker.tsx
new file mode 100644
index 0000000000..86ef91f68c
--- /dev/null
+++ b/apps/web/src/features/settings/PipedreamAppPicker.tsx
@@ -0,0 +1,256 @@
+import { PipedreamConnectorIcon } from '@core/pipedream/ConnectorIcon';
+import {
+ createPipedreamCatalogConnect,
+ createPipedreamCatalogSearch,
+} from '@core/pipedream/catalog';
+import SpinnerIcon from '@phosphor/spinner-gap.svg';
+import XIcon from '@phosphor/x.svg';
+import type { PipedreamCatalogEntryResponse } from '@service-cognition/client';
+import type { AgentMcpServer } from '@service-storage/generated/schemas/agentMcpServer';
+import { Button } from '@ui';
+import { type Accessor, createMemo, For, Show } from 'solid-js';
+import {
+ addMcpServer,
+ catalogEntryToMcpServer,
+ mcpServerConnectionState,
+ removeMcpServer,
+} from './agentMcpServers';
+import { ConnectAction, StatusDot } from './integration-ui';
+import { IntegrationRow } from './primitives';
+
+/**
+ * Picks Pipedream apps for an agent from the whole catalog, connected or
+ * not, and shows for each picked app whether the *viewer* has connected it.
+ *
+ * Selection is the agent's; connection is personal. A teammate opening the
+ * same agent sees their own dots, because a session spends the connections
+ * of whoever runs it. So an unconnected pick is never an error here - it is
+ * the agent's author saying "this agent uses Linear", and each person
+ * connects Linear on their own, from this row or from Settings → Connections.
+ */
+export function PipedreamAppPicker(props: {
+ selected: readonly AgentMcpServer[];
+ onChange: (servers: AgentMcpServer[]) => void;
+ /** The viewer's connected app slugs. */
+ connectedSlugs: Accessor<ReadonlySet<string>>;
+ /** False while the viewer's connections are still loading. */
+ connectionsReady: Accessor<boolean>;
+ /** Where the Connect iframe mounts; the enclosing dialog's content. */
+ connectContainer: Accessor<HTMLElement | undefined>;
+}) {
+ const selectedSlugs = createMemo<ReadonlySet<string>>(
+ () => new Set(props.selected.map((server) => server.app_slug))
+ );
+ const catalog = createPipedreamCatalogSearch(selectedSlugs);
+ const searching = () => catalog.searchInput().trim().length > 0;
+
+ const pick = (entry: PipedreamCatalogEntryResponse) => {
+ props.onChange(
+ addMcpServer(props.selected, catalogEntryToMcpServer(entry))
+ );
+ catalog.onSearchInput('');
+ };
+
+ return (
+ <div class="flex flex-col gap-3">
+ <input
+ type="search"
+ aria-label="Search connectors"
+ class="settings-input w-full"
+ placeholder="Search all connectors…"
+ value={catalog.searchInput()}
+ onInput={(event) => catalog.onSearchInput(event.currentTarget.value)}
+ />
+
+ <Show when={searching()}>
+ <div
+ role="listbox"
+ aria-label="Connector results"
+ class="max-h-64 overflow-y-auto rounded-lg border border-edge-muted"
+ >
+ <Show when={catalog.query.isError}>
+ <div class="px-4 py-4 text-center text-sm text-ink-muted">
+ Couldn't load the connector catalog.
+ <Button
+ variant="outline"
+ size="sm"
+ depth={3}
+ onClick={() => catalog.query.refetch()}
+ class="ml-2"
+ >
+ Retry
+ </Button>
+ </div>
+ </Show>
+ <Show when={!catalog.query.isError}>
+ <For each={catalog.entries()}>
+ {(entry) => (
+ <CatalogResult
+ entry={entry}
+ connected={props.connectedSlugs().has(entry.app_slug)}
+ onPick={() => pick(entry)}
+ />
+ )}
+ </For>
+ <Show
+ when={catalog.query.isFetching && catalog.entries().length === 0}
+ >
+ <div class="px-4 py-4 text-center text-sm text-ink-muted">
+ Loading connectors…
+ </div>
+ </Show>
+ <Show
+ when={
+ !catalog.query.isFetching &&
+ catalog.entries().length === 0 &&
+ catalog.search().trim()
+ }
+ >
+ <div class="px-4 py-4 text-center text-sm text-ink-muted">
+ No connectors found for "{catalog.search().trim()}".
+ </div>
+ </Show>
+ <Show when={catalog.query.hasNextPage}>
+ <div class="px-3 py-2 text-center">
+ <Button
+ variant="outline"
+ size="sm"
+ depth={3}
+ disabled={catalog.query.isFetchingNextPage}
+ onClick={() => void catalog.query.fetchNextPage()}
+ >
+ {catalog.query.isFetchingNextPage ? 'Loading…' : 'Load more'}
+ </Button>
+ </div>
+ </Show>
+ </Show>
+ </div>
+ </Show>
+
+ <Show
+ when={props.selected.length > 0}
+ fallback={
+ <p class="text-xs text-ink-extra-muted">
+ No apps selected yet. Search above to add one.
+ </p>
+ }
+ >
+ <div class="divide-y divide-edge-muted rounded-lg border border-edge-muted">
+ <For each={props.selected}>
+ {(server) => (
+ <SelectedAppRow
+ server={server}
+ connectedSlugs={props.connectedSlugs}
+ connectionsReady={props.connectionsReady}
+ connectContainer={props.connectContainer}
+ onRemove={() =>
+ props.onChange(
+ removeMcpServer(props.selected, server.app_slug)
+ )
+ }
+ />
+ )}
+ </For>
+ </div>
+ </Show>
+ </div>
+ );
+}
+
+function CatalogResult(props: {
+ entry: PipedreamCatalogEntryResponse;
+ connected: boolean;
+ onPick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ role="option"
+ aria-selected={false}
+ class="flex w-full items-center gap-3 px-3 py-2 text-left hover:bg-hover focus-visible:bg-active outline-none"
+ onClick={() => props.onPick()}
+ >
+ <PipedreamConnectorIcon
+ appSlug={props.entry.app_slug}
+ iconUrl={props.entry.icon_url}
+ class="size-4"
+ />
+ <span class="min-w-0 flex-1">
+ <span class="block truncate text-sm text-ink">
+ {props.entry.display_name}
+ </span>
+ <Show when={props.entry.description}>
+ <span class="block truncate text-xs text-ink-muted">
+ {props.entry.description}
+ </span>
+ </Show>
+ </span>
+ <Show when={props.connected}>
+ <span class="flex items-center gap-1.5 text-xs text-ink-muted">
+ <StatusDot state="connected" label="Connected" />
+ Connected
+ </span>
+ </Show>
+ </button>
+ );
+}
+
+function SelectedAppRow(props: {
+ server: AgentMcpServer;
+ connectedSlugs: Accessor<ReadonlySet<string>>;
+ connectionsReady: Accessor<boolean>;
+ connectContainer: Accessor<HTMLElement | undefined>;
+ onRemove: () => void;
+}) {
+ const state = () =>
+ mcpServerConnectionState(props.server, props.connectedSlugs());
+ const { connect, busy } = createPipedreamCatalogConnect({
+ entry: () => ({
+ app_slug: props.server.app_slug,
+ display_name: props.server.server_name,
+ }),
+ container: props.connectContainer,
+ });
+
+ return (
+ <IntegrationRow
+ class="px-3 py-2.5"
+ icon={
+ <PipedreamConnectorIcon
+ appSlug={props.server.app_slug}
+ class="size-5"
+ />
+ }
+ title={props.server.server_name}
+ description={props.server.app_slug}
+ status={
+ <Show
+ when={props.connectionsReady()}
+ fallback={<SpinnerIcon class="size-3 animate-spin text-ink-muted" />}
+ >
+ <StatusDot
+ state={state()}
+ label={state() === 'connected' ? 'Connected' : 'Not connected'}
+ />
+ </Show>
+ }
+ >
+ <Show when={props.connectionsReady() && state() === 'disconnected'}>
+ <ConnectAction
+ label="Connect"
+ loading={busy()}
+ onClick={() => void connect()}
+ />
+ </Show>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={`Remove ${props.server.server_name}`}
+ onClick={() => props.onRemove()}
+ >
+ <XIcon />
+ </Button>
+ </IntegrationRow>
+ );
+}
diff --git a/apps/web/src/features/settings/PipedreamIntegrations.tsx b/apps/web/src/features/settings/PipedreamIntegrations.tsx
index c23c950e53..c1439f4322 100644
--- a/apps/web/src/features/settings/PipedreamIntegrations.tsx
+++ b/apps/web/src/features/settings/PipedreamIntegrations.tsx
@@ -5,9 +5,14 @@ import {
createPipedreamCatalogConnect,
createPipedreamCatalogSearch,
} from '@core/pipedream/catalog';
+import {
+ clearPendingConnectApp,
+ pendingConnectApp,
+} from '@core/pipedream/pendingConnect';
import PlugIcon from '@phosphor-icons/core/regular/plug.svg?component-solid';
import XIcon from '@phosphor-icons/core/regular/x.svg?component-solid';
import {
+ connectPipedreamApp,
useDeletePipedreamConnectionMutation,
usePipedreamConnectionsQuery,
useUpdatePipedreamConnectionMutation,
@@ -17,7 +22,14 @@ import type {
PipedreamConnectionResponse,
} from '@service-cognition/client';
import { Button, ToggleSwitch } from '@ui';
-import { createMemo, createSignal, For, Show } from 'solid-js';
+import {
+ createEffect,
+ createMemo,
+ createSignal,
+ For,
+ on,
+ Show,
+} from 'solid-js';
import { ConnectAction } from './integration-ui';
import { IntegrationRow, SettingsCard, SettingsSection } from './primitives';
@@ -156,6 +168,25 @@ export function PipedreamIntegrationsSection() {
() => new Set(servers().map((s) => s.app_slug))
);
+ // An agent reply's "Connect X" chip asks for one app to be connected and
+ // opens this page; start that app's Connect flow as soon as the request is
+ // seen, whether this section mounted for it or was already showing. An
+ // effect because this drives an imperative flow (the hosted iframe), not
+ // derived state.
+ createEffect(
+ on(pendingConnectApp, (requested) => {
+ if (!requested) return;
+ clearPendingConnectApp();
+ void connectPipedreamApp({ appSlug: requested })
+ .then((outcome) => {
+ if (outcome === 'unsupported') {
+ toast.failure('Connectors are not available on this deployment');
+ }
+ })
+ .catch(() => toast.failure(`Failed to connect ${requested}`));
+ })
+ );
+
const catalog = createPipedreamCatalogSearch(connectedSlugs);
const catalogQuery = catalog.query;
const browseResults = catalog.entries;
diff --git a/apps/web/src/features/settings/agentMcpServers.test.ts b/apps/web/src/features/settings/agentMcpServers.test.ts
new file mode 100644
index 0000000000..f036d7e63a
--- /dev/null
+++ b/apps/web/src/features/settings/agentMcpServers.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest';
+import {
+ addMcpServer,
+ catalogEntryToMcpServer,
+ mcpServerConnectionState,
+ removeMcpServer,
+} from './agentMcpServers';
+
+const linear = { app_slug: 'linear', server_name: 'Linear' };
+const notion = { app_slug: 'notion', server_name: 'Notion' };
+
+describe('agentMcpServers', () => {
+ it('reduces a catalog entry to the stored shape', () => {
+ expect(
+ catalogEntryToMcpServer({
+ app_slug: 'linear',
+ display_name: 'Linear',
+ })
+ ).toEqual(linear);
+ });
+
+ it('adds by slug without duplicating', () => {
+ expect(addMcpServer([], linear)).toEqual([linear]);
+ expect(addMcpServer([linear], notion)).toEqual([linear, notion]);
+ expect(
+ addMcpServer([linear], { app_slug: 'linear', server_name: 'Other' })
+ ).toEqual([linear]);
+ });
+
+ it('removes by slug', () => {
+ expect(removeMcpServer([linear, notion], 'linear')).toEqual([notion]);
+ expect(removeMcpServer([linear], 'missing')).toEqual([linear]);
+ });
+
+ it('reads connection state from the viewer set', () => {
+ const connected = new Set(['linear']);
+ expect(mcpServerConnectionState(linear, connected)).toBe('connected');
+ expect(mcpServerConnectionState(notion, connected)).toBe('disconnected');
+ });
+});
diff --git a/apps/web/src/features/settings/agentMcpServers.ts b/apps/web/src/features/settings/agentMcpServers.ts
new file mode 100644
index 0000000000..9fda51909c
--- /dev/null
+++ b/apps/web/src/features/settings/agentMcpServers.ts
@@ -0,0 +1,39 @@
+import type { AgentMcpServer } from '@service-storage/generated/schemas/agentMcpServer';
+import type { ConnectionState } from './integration-ui';
+
+/** A catalog entry reduced to what the agent stores. */
+export function catalogEntryToMcpServer(entry: {
+ app_slug: string;
+ display_name: string;
+}): AgentMcpServer {
+ return { app_slug: entry.app_slug, server_name: entry.display_name };
+}
+
+/** Appends `server` unless an entry with its slug is already listed. */
+export function addMcpServer(
+ list: readonly AgentMcpServer[],
+ server: AgentMcpServer
+): AgentMcpServer[] {
+ if (list.some((existing) => existing.app_slug === server.app_slug)) {
+ return [...list];
+ }
+ return [...list, server];
+}
+
+export function removeMcpServer(
+ list: readonly AgentMcpServer[],
+ appSlug: string
+): AgentMcpServer[] {
+ return list.filter((server) => server.app_slug !== appSlug);
+}
+
+/**
+ * How a listed app reads for the viewer: connected if they hold a connection
+ * for it, otherwise not. Selection is the agent's; connection is personal.
+ */
+export function mcpServerConnectionState(
+ server: AgentMcpServer,
+ connectedSlugs: ReadonlySet<string>
+): ConnectionState {
+ return connectedSlugs.has(server.app_slug) ? 'connected' : 'disconnected';
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
index 5bad5fc3a9..91066ce46e 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
@@ -14,6 +14,7 @@ import {
type AgentContextNode,
type AwaitNode,
type ClassedBlockNode,
+ type ConnectAppNode,
type ContactMentionNode,
type DateMentionNode,
DEFAULT_LANGUAGE,
@@ -77,6 +78,7 @@ import { forceSingleLine, setEditorStateFromMarkdown } from '../../utils';
import { StaticCodeBoxAccessory } from '../accessory/CodeBoxAccessory';
import { AgentContext as AgentContextDecorator } from '../decorator/AgentContext';
import { Await as AwaitDecorator } from '../decorator/Await';
+import { ConnectApp as ConnectAppDecorator } from '../decorator/ConnectApp';
import { ContactMention as ContactMentionDecorator } from '../decorator/ContactMention';
import { DateMention as DateMentionDecorator } from '../decorator/DateMention';
import { DocumentCard as DocumentCardDecorator } from '../decorator/DocumentCard';
@@ -407,6 +409,20 @@ const ThemeMention: TypedRenderableEntity<ThemeMentionNode> = {
),
};
+const ConnectApp: TypedRenderableEntity<ConnectAppNode> = {
+ guard: (node: LexicalNode): node is ConnectAppNode =>
+ node.__type === 'connect-app',
+ render: (props) => (
+ <span>
+ {ConnectAppDecorator({
+ ...props.node.exportComponentProps(),
+ key: props.node.getKey(),
+ theme: props.theme,
+ })}
+ </span>
+ ),
+};
+
const TagMention: TypedRenderableEntity<TagMentionNode> = {
guard: (node: LexicalNode): node is TagMentionNode =>
node.__type === 'tag-mention',
@@ -903,6 +919,7 @@ const InlineEntities: RenderableEntity[] = [
eraseRenderableEntity(Equation),
eraseRenderableEntity(ThemeMention),
eraseRenderableEntity(TagMention),
+ eraseRenderableEntity(ConnectApp),
eraseRenderableEntity(UnknownMention),
eraseRenderableEntity(Watermark),
eraseRenderableEntity(Paste),
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsx
new file mode 100644
index 0000000000..c6f42a784c
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsx
@@ -0,0 +1,67 @@
+import { useSettingsState } from '@core/constant/SettingsState';
+import { PipedreamConnectorIcon } from '@core/pipedream/ConnectorIcon';
+import { requestConnectApp } from '@core/pipedream/pendingConnect';
+import type { ConnectAppDecoratorProps } from '@macro-inc/lexical-core';
+import ArrowUpRightIcon from '@phosphor/arrow-up-right.svg';
+import { usePipedreamConnectedSlugs } from '@queries/pipedream-connectors';
+import { cn } from '@ui';
+import { Show, useContext } from 'solid-js';
+import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
+
+/**
+ * The chip an agent's reply renders when a tool call failed because the
+ * reader has not connected an app. Clicking it opens Settings → Connections
+ * with that app queued to connect. Once the reader has connected it, the same
+ * chip reads as connected rather than nagging.
+ */
+export function ConnectApp(props: ConnectAppDecoratorProps) {
+ const { openSettings } = useSettingsState();
+ const connections = usePipedreamConnectedSlugs();
+ const lexicalWrapper = useContext(LexicalWrapperContext);
+ const selection = () => lexicalWrapper?.selection;
+ const connected = () =>
+ connections.ready() && connections.slugs().has(props.appSlug);
+
+ const isSelectedAsNode = () => {
+ const sel = selection();
+ if (!sel) return false;
+ return sel.type === 'node' && sel.nodeKeys.has(props.key);
+ };
+
+ const handleClick = () => {
+ if (connected()) return;
+ // The Connections page picks this up and starts the Connect flow.
+ requestConnectApp(props.appSlug);
+ openSettings('Connected');
+ };
+
+ return (
+ <button
+ type="button"
+ data-connect-app={props.appSlug}
+ aria-label={
+ connected() ? `${props.name} connected` : `Connect ${props.name}`
+ }
+ class={cn(
+ 'pointer-events-auto inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 align-middle text-xs font-medium',
+ 'cursor-default outline-none transition-colors',
+ connected()
+ ? 'border-edge-muted text-ink-muted'
+ : 'border-accent/40 text-accent hover:bg-accent/10 focus-visible:bg-accent/10',
+ isSelectedAsNode() && 'bg-active'
+ )}
+ // Keep the editor's selection where it was: this is an action, not a
+ // caret target.
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={handleClick}
+ >
+ <PipedreamConnectorIcon appSlug={props.appSlug} class="size-3.5" />
+ <Show when={connected()} fallback={<>Connect {props.name}</>}>
+ {props.name} connected
+ </Show>
+ <Show when={!connected()}>
+ <ArrowUpRightIcon class="size-3 opacity-70" />
+ </Show>
+ </button>
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/init.ts b/apps/web/src/lib/core/component/LexicalMarkdown/init.ts
index 061e907e4c..daa1c6a773 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/init.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/init.ts
@@ -1,6 +1,7 @@
import {
AgentContextNode,
AwaitNode,
+ ConnectAppNode,
ContactMentionNode,
DateMentionNode,
DiffInsertNode,
@@ -29,6 +30,7 @@ import {
} from '@macro-inc/lexical-core/decoratorRegistry';
import { AgentContext } from './component/decorator/AgentContext';
import { Await } from './component/decorator/Await';
+import { ConnectApp } from './component/decorator/ConnectApp';
import { ContactMention } from './component/decorator/ContactMention';
import { DateMention } from './component/decorator/DateMention';
import { DiffInsert } from './component/decorator/DiffInsert';
@@ -75,6 +77,7 @@ export function initializeLexical() {
setDecorator(SnapshotNode, Snapshot);
setDecorator(HtmlRenderNode, HtmlRender);
setDecorator(ThemeMentionNode, ThemeMention);
+ setDecorator(ConnectAppNode, ConnectApp);
setDecorator(TagMentionNode, TagMention);
setDecorator(UnknownMentionNode, UnknownMention);
setDecorator(WatermarkNode, Watermark);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
index d4fb6f1a78..5b2786103d 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
@@ -18,5 +18,6 @@
* Version 2.5 - Aug 2026. Added expandable AgentContextNode.
* Version 2.6 - Aug 2026. PasteNode origin: pasted (default) or referenced.
* Version 3.0 - Sep 2026. Added ReplyTargetNode.
+ * Version 3.1 - Sep 2026. Added ConnectAppNode (agent "connect this app" chip).
*/
-export const MARKDOWN_VERSION_COUNTER = 3.0;
+export const MARKDOWN_VERSION_COUNTER = 3.1;
diff --git a/apps/web/src/lib/core/pipedream/catalog.ts b/apps/web/src/lib/core/pipedream/catalog.ts
index 7dcd4e304c..ba75e5b600 100644
--- a/apps/web/src/lib/core/pipedream/catalog.ts
+++ b/apps/web/src/lib/core/pipedream/catalog.ts
@@ -49,15 +49,25 @@ export function createPipedreamCatalogSearch(
return { searchInput, onSearchInput, search, query, entries };
}
+/** The two facts connecting needs: which app, and what to call it. */
+export type PipedreamConnectableApp = Pick<
+ PipedreamCatalogEntryResponse,
+ 'app_slug' | 'display_name'
+>;
+
/**
* Connecting one catalog entry through Pipedream's hosted Connect UI, with
* the toasts every surface wants. Success needs no toast of its own on
* surfaces that re-render the row as connected, so callers opt in via
* `onConnected`.
*/
-export function createPipedreamCatalogConnect(options: {
- entry: Accessor<PipedreamCatalogEntryResponse>;
- onConnected?: (entry: PipedreamCatalogEntryResponse) => void;
+export function createPipedreamCatalogConnect<
+ App extends PipedreamConnectableApp,
+>(options: {
+ entry: Accessor<App>;
+ onConnected?: (entry: App) => void;
+ /** Where the Connect iframe mounts; see `openPipedreamConnectUI`. */
+ container?: Accessor<HTMLElement | undefined>;
}) {
const [busy, setBusy] = createSignal(false);
@@ -69,6 +79,7 @@ export function createPipedreamCatalogConnect(options: {
const outcome = await connectPipedreamApp({
appSlug: entry.app_slug,
serverName: entry.display_name,
+ container: options.container?.(),
});
if (outcome === 'connected') {
options.onConnected?.(entry);
diff --git a/apps/web/src/lib/core/pipedream/connect-ui.ts b/apps/web/src/lib/core/pipedream/connect-ui.ts
index bc359a6ae1..be4836f926 100644
--- a/apps/web/src/lib/core/pipedream/connect-ui.ts
+++ b/apps/web/src/lib/core/pipedream/connect-ui.ts
@@ -36,6 +36,13 @@ export function openPipedreamConnectUI(options: {
/** The Pipedream app to connect, by name slug (e.g. `linear`). */
app: string;
onEvent: (event: PipedreamConnectEvent) => void;
+ /**
+ * Where the iframe mounts; `document.body` by default. A modal dialog
+ * disables pointer events on the body and traps focus inside its content,
+ * so a surface opening this from inside one passes the dialog's content
+ * element to keep the iframe clickable and typeable.
+ */
+ container?: HTMLElement;
}): PipedreamConnectUI {
const params = new URLSearchParams({
token: options.token,
@@ -78,7 +85,7 @@ export function openPipedreamConnectUI(options: {
};
window.addEventListener('message', onMessage);
- document.body.appendChild(iframe);
+ (options.container ?? document.body).appendChild(iframe);
return { close: cleanup };
}
diff --git a/apps/web/src/lib/core/pipedream/pendingConnect.ts b/apps/web/src/lib/core/pipedream/pendingConnect.ts
new file mode 100644
index 0000000000..d974b64ec0
--- /dev/null
+++ b/apps/web/src/lib/core/pipedream/pendingConnect.ts
@@ -0,0 +1,23 @@
+import { createSignal } from 'solid-js';
+
+/**
+ * An app somebody asked to connect from outside the Connections page (an
+ * agent reply's "Connect X" chip). The chip sets it and opens Settings →
+ * Connections; the Pipedream section there consumes it and starts the
+ * Connect flow. A signal rather than a URL parameter because the settings
+ * layout rebuilds its URL from split state and drops query strings.
+ */
+const [pendingConnectApp, setPendingConnectApp] = createSignal<string>();
+
+/** Ask the Connections page to start connecting `appSlug` once it shows. */
+export function requestConnectApp(appSlug: string) {
+ setPendingConnectApp(appSlug);
+}
+
+/** The app slug waiting to be connected, if any. */
+export { pendingConnectApp };
+
+/** Mark the pending request as taken so it runs exactly once. */
+export function clearPendingConnectApp() {
+ setPendingConnectApp(undefined);
+}
diff --git a/apps/web/src/lib/queries/agents/agents.test.tsx b/apps/web/src/lib/queries/agents/agents.test.tsx
index f019118bfc..3721dac5bb 100644
--- a/apps/web/src/lib/queries/agents/agents.test.tsx
+++ b/apps/web/src/lib/queries/agents/agents.test.tsx
@@ -43,6 +43,7 @@ const params: CreateAgentParams = {
harness: 'in-memory',
name: 'Bug fixer',
instructions: 'Fix bugs.',
+ mcp: { scope: 'owner_connections' },
};
function agent(channelIds: string[]): Agent {
@@ -62,6 +63,7 @@ function agent(channelIds: string[]): Agent {
default_model: 'claude-sonnet-4-5',
channel_scope: 'selected',
channel_ids: channelIds,
+ mcp: { scope: 'owner_connections' },
};
}
diff --git a/apps/web/src/lib/queries/agents/agents.ts b/apps/web/src/lib/queries/agents/agents.ts
index 42451f533b..ff61dc1e8d 100644
--- a/apps/web/src/lib/queries/agents/agents.ts
+++ b/apps/web/src/lib/queries/agents/agents.ts
@@ -5,6 +5,7 @@ import { queryClient } from '@queries/client';
import { storageServiceClient } from '@service-storage/client';
import type { Agent } from '@service-storage/generated/schemas/agent';
import type { AgentChannelScope } from '@service-storage/generated/schemas/agentChannelScope';
+import type { AgentMcpServers } from '@service-storage/generated/schemas/agentMcpServers';
import { useMutation, useQuery } from '@tanstack/solid-query';
import { agentKeys } from './keys';
@@ -26,6 +27,8 @@ export type CreateAgentParams = {
harnessId?: string;
name: string;
instructions: string;
+ /** Which Pipedream MCP servers the agent's sessions are handed. */
+ mcp: AgentMcpServers;
teamId?: string;
};
@@ -76,6 +79,7 @@ export function useCreateAgentMutation() {
harness_id: vars.harnessId,
name: vars.name,
instructions: vars.instructions,
+ mcp: vars.mcp,
team_id: vars.teamId,
})
),
@@ -107,6 +111,7 @@ export function useUpdateAgentMutation() {
harness_id: vars.harnessId,
name: vars.name,
instructions: vars.instructions,
+ mcp: vars.mcp,
team_id: vars.teamId,
})
),
diff --git a/apps/web/src/lib/queries/pipedream-connectors.ts b/apps/web/src/lib/queries/pipedream-connectors.ts
index 329ae4d8de..8511952187 100644
--- a/apps/web/src/lib/queries/pipedream-connectors.ts
+++ b/apps/web/src/lib/queries/pipedream-connectors.ts
@@ -14,6 +14,7 @@ import {
useMutation,
useQuery,
} from '@tanstack/solid-query';
+import { type Accessor, createMemo } from 'solid-js';
const KEYS = {
all: ['pipedreamConnectors'] as const,
@@ -48,6 +49,35 @@ export function usePipedreamConnectionsQuery(options?: {
}));
}
+/**
+ * The app slugs the current user has connected, as a set, plus whether the
+ * answer is known yet. `ready` is false while the query is still serving the
+ * `neverSuspend` placeholder, which callers must not read as "connected to
+ * nothing". Shared by every surface that shows a connected/not-connected
+ * indicator so they cannot disagree.
+ */
+export function usePipedreamConnectedSlugs(options?: {
+ refetchInterval?: number;
+}): {
+ slugs: Accessor<ReadonlySet<string>>;
+ ready: Accessor<boolean>;
+} {
+ const query = usePipedreamConnectionsQuery({
+ neverSuspend: true,
+ refetchInterval: options?.refetchInterval,
+ });
+ const slugs = createMemo<ReadonlySet<string>>(
+ () =>
+ new Set(
+ (query.isSuccess ? query.data : NO_CONNECTIONS).map(
+ (connection) => connection.app_slug
+ )
+ )
+ );
+ const ready = () => !query.isPlaceholderData && !query.isPending;
+ return { slugs, ready };
+}
+
/**
* Browse or search the Pipedream app catalog, paged by cursor. Entries come
* from Pipedream's app directory, ranked most-popular-first.
@@ -160,6 +190,8 @@ export async function connectPipedreamApp(args: {
appSlug: string;
/** Display name stored on the connection row. */
serverName?: string;
+ /** Where the Connect iframe mounts; see `openPipedreamConnectUI`. */
+ container?: HTMLElement;
}): Promise<PipedreamConnectOutcome> {
if (pipedreamUnsupported) return 'unsupported';
@@ -177,6 +209,7 @@ export async function connectPipedreamApp(args: {
const ui = openPipedreamConnectUI({
token: token.value.token,
app: args.appSlug,
+ container: args.container,
onEvent: (event) => {
if (event.type === 'success' && !settled) {
settled = true;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.ts
index 88f439df93..0ccdc5e7c3 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agent.ts
@@ -7,6 +7,7 @@
import type { AgentChannelScope } from './agentChannelScope';
import type { AgentHarnessId } from './agentHarnessId';
+import type { AgentMcpServers } from './agentMcpServers';
import type { Bot } from './bot';
/**
@@ -26,4 +27,6 @@ export interface Agent {
harness_id?: AgentHarnessId;
/** Instructions supplied to the agent at the start of a conversation. */
instructions: string;
+ /** Which MCP servers sessions of this agent are handed. */
+ mcp: AgentMcpServers;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServer.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServer.ts
new file mode 100644
index 0000000000..c9476356f8
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServer.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * One Pipedream app an agent lists under [`AgentMcpServers::Selected`].
+
+Only the catalog identity is stored. Whether a given person has connected
+the app is theirs, resolved at call time by the egress proxy, never here.
+ */
+export interface AgentMcpServer {
+ /** Pipedream app slug, e.g. `linear`. */
+ app_slug: string;
+ /** Display name, e.g. `Linear`. */
+ server_name: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServers.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServers.ts
new file mode 100644
index 0000000000..2766d104cd
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServers.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentMcpServersOneOf } from './agentMcpServersOneOf';
+import type { AgentMcpServersOneOfThree } from './agentMcpServersOneOfThree';
+
+/**
+ * Which Pipedream MCP servers an agent's sessions are handed.
+
+One value for the whole choice, so a selection can never travel without
+its scope or a scope without its selection. Serialized with a `scope` tag,
+which the generated TypeScript sees as a discriminated union.
+ */
+export type AgentMcpServers = AgentMcpServersOneOf | AgentMcpServersOneOfThree;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServersOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServersOneOf.ts
new file mode 100644
index 0000000000..2e45fb983c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServersOneOf.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentMcpServersOneOfScope } from './agentMcpServersOneOfScope';
+
+/**
+ * Whatever apps the person running the session has connected.
+ */
+export type AgentMcpServersOneOf = {
+ scope: AgentMcpServersOneOfScope;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServersOneOfScope.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServersOneOfScope.ts
new file mode 100644
index 0000000000..307cbdf0c9
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServersOneOfScope.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type AgentMcpServersOneOfScope =
+ (typeof AgentMcpServersOneOfScope)[keyof typeof AgentMcpServersOneOfScope];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentMcpServersOneOfScope = {
+ owner_connections: 'owner_connections',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServersOneOfThree.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServersOneOfThree.ts
new file mode 100644
index 0000000000..640823bdcd
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServersOneOfThree.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { AgentMcpServer } from './agentMcpServer';
+import type { AgentMcpServersOneOfThreeScope } from './agentMcpServersOneOfThreeScope';
+
+/**
+ * Exactly these apps, connected or not.
+ */
+export type AgentMcpServersOneOfThree = {
+ scope: AgentMcpServersOneOfThreeScope;
+ /** The apps, in the order the agent's author picked them. */
+ servers: AgentMcpServer[];
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServersOneOfThreeScope.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServersOneOfThreeScope.ts
new file mode 100644
index 0000000000..3f8ecc9f01
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentMcpServersOneOfThreeScope.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type AgentMcpServersOneOfThreeScope =
+ (typeof AgentMcpServersOneOfThreeScope)[keyof typeof AgentMcpServersOneOfThreeScope];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentMcpServersOneOfThreeScope = {
+ selected: 'selected',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.ts
index d502af2d9b..829304925f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createAgentRequest.ts
@@ -6,6 +6,7 @@
*/
import type { AgentChannelScope } from './agentChannelScope';
+import type { AgentMcpServers } from './agentMcpServers';
import type { CreateAgentRequestAvatarUrl } from './createAgentRequestAvatarUrl';
import type { CreateAgentRequestDescription } from './createAgentRequestDescription';
import type { CreateAgentRequestHarnessId } from './createAgentRequestHarnessId';
@@ -32,6 +33,8 @@ export interface CreateAgentRequest {
harness_id?: CreateAgentRequestHarnessId;
/** Instructions supplied to the agent at the start of a conversation. */
instructions: string;
+ /** Which MCP servers sessions of this agent are handed. */
+ mcp?: AgentMcpServers;
/** Display name. */
name: string;
/** Team owner. Omit for a private, user-owned agent. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 360ac76343..a237ecff64 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -16,6 +16,12 @@ export * from './addPinRequest';
export * from './agent';
export * from './agentChannelScope';
export * from './agentHarnessId';
+export * from './agentMcpServer';
+export * from './agentMcpServers';
+export * from './agentMcpServersOneOf';
+export * from './agentMcpServersOneOfScope';
+export * from './agentMcpServersOneOfThree';
+export * from './agentMcpServersOneOfThreeScope';
export * from './anchor';
export * from './anchorId';
export * from './anchorIdOneOf';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.ts
index 90ba9fe239..51b96ba30f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateAgentRequest.ts
@@ -6,6 +6,7 @@
*/
import type { AgentChannelScope } from './agentChannelScope';
+import type { AgentMcpServers } from './agentMcpServers';
import type { UpdateAgentRequestAvatarUrl } from './updateAgentRequestAvatarUrl';
import type { UpdateAgentRequestDescription } from './updateAgentRequestDescription';
import type { UpdateAgentRequestHarnessId } from './updateAgentRequestHarnessId';
@@ -32,6 +33,8 @@ export interface UpdateAgentRequest {
harness_id?: UpdateAgentRequestHarnessId;
/** Instructions supplied to the agent at the start of a conversation. */
instructions: string;
+ /** Which MCP servers sessions of this agent are handed. */
+ mcp?: AgentMcpServers;
/** Display name. */
name: string;
/** Team owner. Omit to make the agent private to the caller. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 59250d8827..61dba9d24f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -77,6 +77,42 @@ export const listAgentsResponseItem = zod
.describe(
'Instructions supplied to the agent at the start of a conversation.'
),
+ mcp: zod
+ .union([
+ zod
+ .object({
+ scope: zod.enum(['owner_connections']),
+ })
+ .describe(
+ 'Whatever apps the person running the session has connected.'
+ ),
+ zod
+ .object({
+ scope: zod.enum(['selected']),
+ servers: zod
+ .array(
+ zod
+ .object({
+ app_slug: zod
+ .string()
+ .describe('Pipedream app slug, e.g. `linear`.'),
+ server_name: zod
+ .string()
+ .describe('Display name, e.g. `Linear`.'),
+ })
+ .describe(
+ 'One Pipedream app an agent lists under [`AgentMcpServers::Selected`].\n\nOnly the catalog identity is stored. Whether a given person has connected\nthe app is theirs, resolved at call time by the egress proxy, never here.'
+ )
+ )
+ .describe(
+ "The apps, in the order the agent's author picked them."
+ ),
+ })
+ .describe('Exactly these apps, connected or not.'),
+ ])
+ .describe(
+ "Which Pipedream MCP servers an agent's sessions are handed.\n\nOne value for the whole choice, so a selection can never travel without\nits scope or a scope without its selection. Serialized with a `scope` tag,\nwhich the generated TypeScript sees as a discriminated union."
+ ),
})
.describe('A persisted user- or team-owned AI agent.');
export const listAgentsResponse = zod.array(listAgentsResponseItem);
@@ -113,6 +149,43 @@ export const createAgentBody = zod
.describe(
'Instructions supplied to the agent at the start of a conversation.'
),
+ mcp: zod
+ .union([
+ zod
+ .object({
+ scope: zod.enum(['owner_connections']),
+ })
+ .describe(
+ 'Whatever apps the person running the session has connected.'
+ ),
+ zod
+ .object({
+ scope: zod.enum(['selected']),
+ servers: zod
+ .array(
+ zod
+ .object({
+ app_slug: zod
+ .string()
+ .describe('Pipedream app slug, e.g. `linear`.'),
+ server_name: zod
+ .string()
+ .describe('Display name, e.g. `Linear`.'),
+ })
+ .describe(
+ 'One Pipedream app an agent lists under [`AgentMcpServers::Selected`].\n\nOnly the catalog identity is stored. Whether a given person has connected\nthe app is theirs, resolved at call time by the egress proxy, never here.'
+ )
+ )
+ .describe(
+ "The apps, in the order the agent's author picked them."
+ ),
+ })
+ .describe('Exactly these apps, connected or not.'),
+ ])
+ .optional()
+ .describe(
+ "Which Pipedream MCP servers an agent's sessions are handed.\n\nOne value for the whole choice, so a selection can never travel without\nits scope or a scope without its selection. Serialized with a `scope` tag,\nwhich the generated TypeScript sees as a discriminated union."
+ ),
name: zod.string().describe('Display name.'),
team_id: zod
.uuid()
@@ -157,6 +230,43 @@ export const updateAgentBody = zod
.describe(
'Instructions supplied to the agent at the start of a conversation.'
),
+ mcp: zod
+ .union([
+ zod
+ .object({
+ scope: zod.enum(['owner_connections']),
+ })
+ .describe(
+ 'Whatever apps the person running the session has connected.'
+ ),
+ zod
+ .object({
+ scope: zod.enum(['selected']),
+ servers: zod
+ .array(
+ zod
+ .object({
+ app_slug: zod
+ .string()
+ .describe('Pipedream app slug, e.g. `linear`.'),
+ server_name: zod
+ .string()
+ .describe('Display name, e.g. `Linear`.'),
+ })
+ .describe(
+ 'One Pipedream app an agent lists under [`AgentMcpServers::Selected`].\n\nOnly the catalog identity is stored. Whether a given person has connected\nthe app is theirs, resolved at call time by the egress proxy, never here.'
+ )
+ )
+ .describe(
+ "The apps, in the order the agent's author picked them."
+ ),
+ })
+ .describe('Exactly these apps, connected or not.'),
+ ])
+ .optional()
+ .describe(
+ "Which Pipedream MCP servers an agent's sessions are handed.\n\nOne value for the whole choice, so a selection can never travel without\nits scope or a scope without its selection. Serialized with a `scope` tag,\nwhich the generated TypeScript sees as a discriminated union."
+ ),
name: zod.string().describe('Display name.'),
team_id: zod
.uuid()
@@ -235,6 +345,42 @@ export const updateAgentResponse = zod
.describe(
'Instructions supplied to the agent at the start of a conversation.'
),
+ mcp: zod
+ .union([
+ zod
+ .object({
+ scope: zod.enum(['owner_connections']),
+ })
+ .describe(
+ 'Whatever apps the person running the session has connected.'
+ ),
+ zod
+ .object({
+ scope: zod.enum(['selected']),
+ servers: zod
+ .array(
+ zod
+ .object({
+ app_slug: zod
+ .string()
+ .describe('Pipedream app slug, e.g. `linear`.'),
+ server_name: zod
+ .string()
+ .describe('Display name, e.g. `Linear`.'),
+ })
+ .describe(
+ 'One Pipedream app an agent lists under [`AgentMcpServers::Selected`].\n\nOnly the catalog identity is stored. Whether a given person has connected\nthe app is theirs, resolved at call time by the egress proxy, never here.'
+ )
+ )
+ .describe(
+ "The apps, in the order the agent's author picked them."
+ ),
+ })
+ .describe('Exactly these apps, connected or not.'),
+ ])
+ .describe(
+ "Which Pipedream MCP servers an agent's sessions are handed.\n\nOne value for the whole choice, so a selection can never travel without\nits scope or a scope without its selection. Serialized with a `scope` tag,\nwhich the generated TypeScript sees as a discriminated union."
+ ),
})
.describe('A persisted user- or team-owned AI agent.');
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 9fe7d858e8..3f64f2a747 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -12656,7 +12656,8 @@
"harness",
"default_model",
"channel_scope",
- "channel_ids"
+ "channel_ids",
+ "mcp"
],
"properties": {
"bot": {
@@ -12697,6 +12698,10 @@
"instructions": {
"type": "string",
"description": "Instructions supplied to the agent at the start of a conversation."
+ },
+ "mcp": {
+ "$ref": "#/components/schemas/AgentMcpServers",
+ "description": "Which MCP servers sessions of this agent are handed."
}
}
},
@@ -12705,6 +12710,55 @@
"description": "Whether an agent is available everywhere or only in selected channels.",
"enum": ["all", "selected"]
},
+ "AgentMcpServer": {
+ "type": "object",
+ "description": "One Pipedream app an agent lists under [`AgentMcpServers::Selected`].\n\nOnly the catalog identity is stored. Whether a given person has connected\nthe app is theirs, resolved at call time by the egress proxy, never here.",
+ "required": ["app_slug", "server_name"],
+ "properties": {
+ "app_slug": {
+ "type": "string",
+ "description": "Pipedream app slug, e.g. `linear`."
+ },
+ "server_name": {
+ "type": "string",
+ "description": "Display name, e.g. `Linear`."
+ }
+ }
+ },
+ "AgentMcpServers": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "Whatever apps the person running the session has connected.",
+ "required": ["scope"],
+ "properties": {
+ "scope": {
+ "type": "string",
+ "enum": ["owner_connections"]
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "Exactly these apps, connected or not.",
+ "required": ["servers", "scope"],
+ "properties": {
+ "scope": {
+ "type": "string",
+ "enum": ["selected"]
+ },
+ "servers": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AgentMcpServer"
+ },
+ "description": "The apps, in the order the agent's author picked them."
+ }
+ }
+ }
+ ],
+ "description": "Which Pipedream MCP servers an agent's sessions are handed.\n\nOne value for the whole choice, so a selection can never travel without\nits scope or a scope without its selection. Serialized with a `scope` tag,\nwhich the generated TypeScript sees as a discriminated union."
+ },
"Anchor": {
"oneOf": [
{
@@ -16552,6 +16606,10 @@
"type": "string",
"description": "Instructions supplied to the agent at the start of a conversation."
},
+ "mcp": {
+ "$ref": "#/components/schemas/AgentMcpServers",
+ "description": "Which MCP servers sessions of this agent are handed."
+ },
"name": {
"type": "string",
"description": "Display name."
@@ -26242,6 +26300,10 @@
"type": "string",
"description": "Instructions supplied to the agent at the start of a conversation."
},
+ "mcp": {
+ "$ref": "#/components/schemas/AgentMcpServers",
+ "description": "Which MCP servers sessions of this agent are handed."
+ },
"name": {
"type": "string",
"description": "Display name."
diff --git a/crates/agent_egress/src/domain/error.rs b/crates/agent_egress/src/domain/error.rs
index 8dd05aee55..dbbd0fa0b0 100644
--- a/crates/agent_egress/src/domain/error.rs
+++ b/crates/agent_egress/src/domain/error.rs
@@ -34,13 +34,21 @@ pub enum EgressError {
#[error("nothing is served at that path: {0}")]
Unroutable(String),
- /// The owner has no server under this slug. Also covers a server the
- /// owner has since disabled or disconnected: from the sandbox's side
- /// those are the same fact, and distinguishing them would report on the
- /// owner's settings to code the model wrote.
- #[error("no connected MCP server named {0}")]
+ /// Nothing can be addressed under this slug for the owner - not even
+ /// unconnected. With Pipedream every valid slug is addressable, so this
+ /// is reserved for a resolver that genuinely has nowhere to send the
+ /// call. An app the owner has not connected is not an error: its
+ /// `tools/call` is answered with a result saying so, and everything else
+ /// is forwarded for them.
+ #[error("no MCP server named {0}")]
UnknownServer(McpServerSlug),
+ /// A request body the proxy had to read was bigger than it will read.
+ /// Only reachable on the path that answers `tools/call` for an
+ /// unconnected app; every other request streams through unread.
+ #[error("request body exceeds what the proxy will read")]
+ RequestTooLarge,
+
/// We cannot mint a credential for the session's repository: our GitHub
/// App is not installed on it, or the installation belongs to somebody
/// with no connection to the session's owner. Not a refusal of anything
diff --git a/crates/agent_egress/src/domain/model.rs b/crates/agent_egress/src/domain/model.rs
index 2df692d26e..531dd03d5e 100644
--- a/crates/agent_egress/src/domain/model.rs
+++ b/crates/agent_egress/src/domain/model.rs
@@ -15,6 +15,8 @@ use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64URL_NO_PAD;
use bytes::Bytes;
use http::header::{self, HeaderMap, HeaderName};
use http::{HeaderValue, Method};
+use http_body_util::BodyExt;
+use http_body_util::Full;
use http_body_util::combinators::UnsyncBoxBody;
use macro_user_id::email::ReadEmailParts;
use macro_user_id::user_id::MacroUserIdStr;
@@ -216,7 +218,10 @@ pub fn is_macro_staff(user: &MacroUserIdStr<'_>) -> bool {
/// What a verified session token entitles its holder to.
///
/// The owner is the whole authorization story: a session spends the
-/// credentials of the person who opened it, and nobody else's.
+/// credentials of the person who opened it, and nobody else's. The listed
+/// servers are not a permission - any slug resolves against the owner's own
+/// connections - only the names the agent's author gave the apps it was
+/// handed, so a refusal can call an app what the person knows it as.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SessionGrant {
/// The session the sandbox is running.
@@ -225,6 +230,151 @@ pub struct SessionGrant {
pub owner: MacroUserIdStr<'static>,
/// The one repository this session works on. Git egress is pinned to it.
pub repo: RepoSlug,
+ /// The apps the agent listed for this session, for naming only.
+ pub mcp_servers: Vec<McpServerListing>,
+}
+
+impl SessionGrant {
+ /// What to call `slug` when speaking to the model: the agent's own name
+ /// for it when the agent listed it, otherwise the slug made readable
+ /// (`google_sheets` → `Google Sheets`).
+ pub fn display_name(&self, slug: &McpServerSlug) -> String {
+ self.mcp_servers
+ .iter()
+ .find(|listing| listing.slug == *slug)
+ .map(|listing| listing.name.clone())
+ .unwrap_or_else(|| readable_slug(slug))
+ }
+}
+
+/// `google_sheets` → `Google Sheets`: the fallback name for an app nobody
+/// gave a display name.
+fn readable_slug(slug: &McpServerSlug) -> String {
+ slug.as_str()
+ .split(['_', '-'])
+ .filter(|word| !word.is_empty())
+ .map(|word| {
+ let mut chars = word.chars();
+ match chars.next() {
+ Some(first) => first.to_uppercase().chain(chars).collect::<String>(),
+ None => String::new(),
+ }
+ })
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+
+/// One app an agent listed for its sessions: the slug the proxy routes on and
+/// the name anything human-facing calls it.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct McpServerListing {
+ /// Pipedream's app slug, verbatim.
+ pub slug: McpServerSlug,
+ /// Display name, e.g. `Linear`.
+ pub name: String,
+}
+
+/// How a destination resolved: to a call the owner's grant backs, or to one
+/// that can be addressed for the owner without any grant behind it.
+///
+/// The second exists because Pipedream scopes a call by user id and app slug
+/// alone, so an app the owner never connected is still *addressable* - and
+/// listing its tools works, only calling them does not. The service decides
+/// what to do with that; the resolver only reports it.
+#[derive(Clone, Debug)]
+pub enum McpResolution {
+ /// The owner holds an enabled connection for this destination.
+ Connected(UpstreamCall),
+ /// The owner holds no enabled connection, but the upstream can be
+ /// addressed for them anyway.
+ Unconnected(UpstreamCall),
+}
+
+/// The most a JSON-RPC request body may be for the proxy to read it.
+///
+/// Only read on the unconnected path, where the proxy has to know the method
+/// to answer `tools/call` itself. MCP requests are small
+/// JSON; the streaming rationale on [`ProxyBody`] is about responses and
+/// packfiles, neither of which is a request body on the MCP route.
+pub const MAX_MCP_REQUEST_BYTES: usize = 1 << 20;
+
+/// The MCP method whose result the model reads as a tool's own answer.
+pub const TOOLS_CALL_METHOD: &str = "tools/call";
+
+/// The parts of a JSON-RPC request the proxy cares about.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct JsonRpcCall {
+ /// The method name.
+ pub method: String,
+ /// The request id, echoed on the response. Absent on notifications,
+ /// which get no response at all.
+ pub id: serde_json::Value,
+}
+
+/// Reads the method and id off a single JSON-RPC request.
+///
+/// `None` for anything else - a notification (no id), a batch, or a body
+/// that is not JSON - all of which the caller forwards untouched, since
+/// there is nothing here to answer in their place.
+pub fn peek_json_rpc(body: &[u8]) -> Option<JsonRpcCall> {
+ let value: serde_json::Value = serde_json::from_slice(body).ok()?;
+ let object = value.as_object()?;
+ let method = object.get("method")?.as_str()?.to_owned();
+ let id = object.get("id")?.clone();
+ if id.is_null() {
+ return None;
+ }
+ Some(JsonRpcCall { method, id })
+}
+
+/// The markup an agent includes in a reply to give the reader a button that
+/// connects the app. Mirrors the frontend's `m-connect-app` Lexical node; the
+/// payload shape is `{"appSlug": ..., "name": ...}`.
+pub const CONNECT_APP_TAG: &str = "m-connect-app";
+
+/// The tool result the proxy answers a `tools/call` with when the session
+/// owner has not connected the app.
+///
+/// A `result` with `isError: true`, not a JSON-RPC `error`: the former is
+/// what MCP clients hand the model as the tool's own answer, the latter is
+/// rendered as a transport failure the model never sees. The wording is our
+/// own fixed text plus the app's slug and display name - the slug already
+/// validated by [`McpServerSlug::parse`], the name from the agent's own
+/// configuration or derived from that slug.
+pub fn not_connected_tool_result(
+ slug: &McpServerSlug,
+ name: &str,
+ id: serde_json::Value,
+) -> ProxyResponse {
+ let payload = serde_json::json!({
+ "appSlug": slug.as_str(),
+ "name": name,
+ });
+ let text = format!(
+ "{name} is not connected for the person running this session, or they have it turned off, so this tool cannot run yet. Tell them so in your reply, and include this exact markup so they get a button that connects it: <{tag}>{payload}</{tag}> Close your reply by asking them to let you know once they have connected {name} so \
+ you can try again - when they do, call this tool again; nothing else needs to change.",
+ name = name,
+ tag = CONNECT_APP_TAG,
+ );
+ let body = serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": id,
+ "result": {
+ "isError": true,
+ "content": [{ "type": "text", "text": text }],
+ },
+ });
+ let bytes = Bytes::from(serde_json::to_vec(&body).expect("a JSON value serializes"));
+ let mut response = http::Response::new(
+ Full::new(bytes)
+ .map_err(|never| match never {})
+ .boxed_unsync(),
+ );
+ response.headers_mut().insert(
+ header::CONTENT_TYPE,
+ HeaderValue::from_static("application/json"),
+ );
+ response
}
/// A GitHub repository, as `owner/name`.
@@ -488,6 +638,27 @@ pub enum McpDestination {
Connected(McpServerSlug),
}
+/// The route Macro's own MCP server is served on.
+pub const MACRO_MCP_PATH: &str = "/mcp-macro";
+
+/// The route prefix a connected app's slug follows.
+pub const CONNECTED_MCP_PATH_PREFIX: &str = "/mcp/";
+
+impl McpDestination {
+ /// Read a destination off a proxy URL's path.
+ ///
+ /// This is how an in-process client names its server: it is handed the
+ /// same egress URLs a sandbox is, so it reads them the same way the
+ /// router does rather than being told the answer a second way.
+ pub fn from_path(path: &str) -> Option<Self> {
+ if path == MACRO_MCP_PATH {
+ return Some(Self::Macro);
+ }
+ let slug = path.strip_prefix(CONNECTED_MCP_PATH_PREFIX)?;
+ McpServerSlug::parse(slug).map(Self::Connected)
+ }
+}
+
/// A resolved destination and the credential to reach it with.
///
/// The fields are private and the constructors validate, so a credential
diff --git a/crates/agent_egress/src/domain/model/test.rs b/crates/agent_egress/src/domain/model/test.rs
index 4fcfd347d8..d979a9f356 100644
--- a/crates/agent_egress/src/domain/model/test.rs
+++ b/crates/agent_egress/src/domain/model/test.rs
@@ -376,3 +376,23 @@ fn a_repeated_git_service_parameter_does_not_escalate() {
})
);
}
+
+#[test]
+fn an_mcp_destination_is_read_off_the_proxy_path() {
+ assert_eq!(
+ McpDestination::from_path("/mcp-macro"),
+ Some(McpDestination::Macro)
+ );
+ assert_eq!(
+ McpDestination::from_path("/mcp/google_sheets"),
+ Some(McpDestination::Connected(
+ McpServerSlug::parse("google_sheets").expect("slug")
+ ))
+ );
+ // A slug outside the charset, a nested path and a stray route all name
+ // nothing, the same as they do at the router.
+ assert_eq!(McpDestination::from_path("/mcp/Not-A-Slug"), None);
+ assert_eq!(McpDestination::from_path("/mcp/a/b"), None);
+ assert_eq!(McpDestination::from_path("/mcp/"), None);
+ assert_eq!(McpDestination::from_path("/git/info/refs"), None);
+}
diff --git a/crates/agent_egress/src/domain/ports.rs b/crates/agent_egress/src/domain/ports.rs
index 0be3100fa1..2e4f4d65c2 100644
--- a/crates/agent_egress/src/domain/ports.rs
+++ b/crates/agent_egress/src/domain/ports.rs
@@ -9,7 +9,8 @@
use crate::domain::error::EgressError;
use crate::domain::model::{
- McpDestination, ProxyRequest, ProxyResponse, RepoSlug, SessionGrant, SessionToken, UpstreamCall,
+ McpDestination, McpResolution, ProxyRequest, ProxyResponse, RepoSlug, SessionGrant,
+ SessionToken, UpstreamCall,
};
use macro_user_id::user_id::MacroUserIdStr;
@@ -37,12 +38,16 @@ pub trait McpCredentials: Send + Sync {
/// The upstream and credential for `destination`, on behalf of `owner`.
///
/// Resolution is scoped to `owner`: a slug that names somebody else's
- /// server is [`EgressError::UnknownServer`], not somebody else's server.
+ /// server is never somebody else's server. [`McpResolution::Connected`]
+ /// when the owner holds an enabled grant; [`McpResolution::Unconnected`]
+ /// when they do not but the upstream can still be addressed for them
+ /// (Pipedream scopes by user and app alone); [`EgressError::UnknownServer`]
+ /// only when the destination cannot be addressed at all.
fn resolve(
&self,
owner: &MacroUserIdStr<'static>,
destination: &McpDestination,
- ) -> impl Future<Output = Result<UpstreamCall, EgressError>> + Send;
+ ) -> impl Future<Output = Result<McpResolution, EgressError>> + Send;
}
/// Mint a credential for git access to one repository.
diff --git a/crates/agent_egress/src/domain/service.rs b/crates/agent_egress/src/domain/service.rs
index 2523b6411f..e7b0fe24d9 100644
--- a/crates/agent_egress/src/domain/service.rs
+++ b/crates/agent_egress/src/domain/service.rs
@@ -1,12 +1,15 @@
//! The service itself: verify, resolve, stamp, forward.
-use http::Uri;
use http::header::AUTHORIZATION;
+use http::{Method, Uri};
+use http_body_util::{BodyExt, Full};
use crate::domain::error::EgressError;
use crate::domain::model::{
- EgressTarget, ProxyRequest, ProxyResponse, SessionToken, ensure_method_allowed, is_macro_staff,
- sanitize_request_headers, sanitize_response_headers,
+ EgressTarget, MAX_MCP_REQUEST_BYTES, McpDestination, McpResolution, McpServerSlug,
+ ProxyRequest, ProxyResponse, SessionToken, TOOLS_CALL_METHOD, ensure_method_allowed,
+ is_macro_staff, not_connected_tool_result, peek_json_rpc, sanitize_request_headers,
+ sanitize_response_headers,
};
use crate::domain::ports::{Forwarder, GithubTokens, McpCredentials, SessionAuthority};
@@ -101,8 +104,29 @@ where
}
let call = match &target {
- EgressTarget::McpServer(destination) => {
- self.credentials.resolve(&grant.owner, destination).await?
+ EgressTarget::McpServer(destination @ McpDestination::Macro) => {
+ match self.credentials.resolve(&grant.owner, destination).await? {
+ McpResolution::Connected(call) | McpResolution::Unconnected(call) => call,
+ }
+ }
+ EgressTarget::McpServer(destination @ McpDestination::Connected(slug)) => {
+ match self.credentials.resolve(&grant.owner, destination).await? {
+ McpResolution::Connected(call) => call,
+ // The owner has no grant for this app, but it can still
+ // be addressed for them: the handshake and tool listing
+ // go through, and a tool call is answered here with a
+ // result the model can act on.
+ McpResolution::Unconnected(call) => {
+ let name = grant.display_name(slug);
+ match Self::answer_unconnected(slug, &name, request).await? {
+ Unconnected::Answered(response) => return Ok(response),
+ Unconnected::Forward(forwarded) => {
+ request = forwarded;
+ call
+ }
+ }
+ }
+ }
}
EgressTarget::GitHubGit { endpoint } => {
// The repository is the grant's, never the request's: a
@@ -164,3 +188,76 @@ where
Ok(response)
}
}
+
+/// What became of a request to an app the owner has not connected.
+enum Unconnected {
+ /// The proxy answered it itself; nothing goes upstream.
+ Answered(ProxyResponse),
+ /// Forward it, addressed for the owner, so the handshake and tool listing
+ /// work. The body has been read and put back.
+ Forward(ProxyRequest),
+}
+
+impl<Sessions, Credentials, Tokens, Forward>
+ EgressServiceImpl<Sessions, Credentials, Tokens, Forward>
+where
+ Sessions: SessionAuthority,
+ Credentials: McpCredentials,
+ Tokens: GithubTokens,
+ Forward: Forwarder,
+{
+ /// An app the owner has not connected: forward everything except
+ /// `tools/call`.
+ ///
+ /// `initialize`, `tools/list`, notifications, the GET event stream and
+ /// DELETE all go to the upstream addressed for the owner, so the agent's
+ /// client completes its handshake and sees the app's real tools from the
+ /// first turn. A `tools/call` is answered here with a tool result that
+ /// names the app and how to connect it - and the moment the owner does,
+ /// the same advertised server resolves as connected and calls flow
+ /// through, with nothing re-attached.
+ async fn answer_unconnected(
+ slug: &McpServerSlug,
+ name: &str,
+ request: ProxyRequest,
+ ) -> Result<Unconnected, EgressError> {
+ if *request.method() != Method::POST {
+ return Ok(Unconnected::Forward(request));
+ }
+ let (parts, mut body) = request.into_parts();
+ let mut bytes = Vec::new();
+ while let Some(frame) = body.frame().await {
+ let frame = frame.map_err(|error| {
+ EgressError::Internal(rootcause::report!(
+ "could not read an MCP request body: {error}"
+ ))
+ })?;
+ if let Ok(data) = frame.into_data() {
+ if bytes.len() + data.len() > MAX_MCP_REQUEST_BYTES {
+ return Err(EgressError::RequestTooLarge);
+ }
+ bytes.extend_from_slice(&data);
+ }
+ }
+ let bytes = bytes::Bytes::from(bytes);
+
+ if let Some(call) = peek_json_rpc(&bytes)
+ && call.method == TOOLS_CALL_METHOD
+ {
+ tracing::info!(
+ app = %slug,
+ "answering tools/call for an app the owner has not connected"
+ );
+ return Ok(Unconnected::Answered(not_connected_tool_result(
+ slug, name, call.id,
+ )));
+ }
+
+ Ok(Unconnected::Forward(ProxyRequest::from_parts(
+ parts,
+ Full::new(bytes)
+ .map_err(|never| match never {})
+ .boxed_unsync(),
+ )))
+ }
+}
diff --git a/crates/agent_egress/src/domain/service/test.rs b/crates/agent_egress/src/domain/service/test.rs
index 10f545853f..05a63d52ca 100644
--- a/crates/agent_egress/src/domain/service/test.rs
+++ b/crates/agent_egress/src/domain/service/test.rs
@@ -1,11 +1,11 @@
use super::*;
use crate::domain::model::{
- AgentSessionId, BearerToken, GitEndpoint, GitService, McpDestination, McpServerSlug, ProxyBody,
- RepoSlug, SessionGrant, UpstreamCall, UpstreamCredential,
+ AgentSessionId, BearerToken, GitEndpoint, GitService, McpDestination, McpServerListing,
+ McpServerSlug, ProxyBody, RepoSlug, SessionGrant, UpstreamCall, UpstreamCredential,
};
use http::header::{AUTHORIZATION, HeaderMap, HeaderName, HeaderValue};
use http::{Method, StatusCode};
-use http_body_util::{BodyExt, Empty};
+use http_body_util::{BodyExt, Empty, Full};
use macro_user_id::user_id::MacroUserIdStr;
use std::sync::Mutex;
use url::Url;
@@ -42,10 +42,16 @@ struct StubSessions(Result<SessionGrant, ()>);
impl StubSessions {
fn granting() -> Self {
+ Self::granting_with(Vec::new())
+ }
+
+ /// A grant whose session was opened by an agent that listed `servers`.
+ fn granting_with(servers: Vec<McpServerListing>) -> Self {
Self(Ok(SessionGrant {
session: AgentSessionId::new(),
owner: owner(),
repo: session_repo(),
+ mcp_servers: servers,
}))
}
@@ -62,10 +68,21 @@ impl SessionAuthority for StubSessions {
}
}
+/// How the spy answers a slug it is asked about.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Knowledge {
+ /// The owner holds an enabled grant.
+ Connected,
+ /// Addressable for the owner, but no grant behind it.
+ Unconnected,
+ /// Nothing to address at all.
+ Unknown,
+}
+
/// Records who it was asked about, and answers with a fixed upstream.
struct SpyCredentials {
asked: Mutex<Vec<(String, String)>>,
- known: bool,
+ known: Knowledge,
url: String,
scope: HeaderMap,
}
@@ -79,12 +96,24 @@ impl SpyCredentials {
fn at(url: &str) -> Self {
Self {
asked: Mutex::default(),
- known: true,
+ known: Knowledge::Connected,
url: url.to_owned(),
scope: HeaderMap::new(),
}
}
+ /// An app the owner has not connected, the way the Pipedream adapter
+ /// reports one: addressable, with the owner's scoping, but no grant.
+ fn unconnected() -> Self {
+ Self {
+ known: Knowledge::Unconnected,
+ ..Self::scoped(&[
+ ("x-pd-external-user-id", "owner"),
+ ("x-pd-app-slug", "datadog"),
+ ])
+ }
+ }
+
/// A resolution that scopes its credential with extra headers, the way
/// the Pipedream adapter does.
fn scoped(scope: &[(&str, &str)]) -> Self {
@@ -104,7 +133,7 @@ impl SpyCredentials {
fn empty() -> Self {
Self {
asked: Mutex::default(),
- known: false,
+ known: Knowledge::Unknown,
url: String::new(),
scope: HeaderMap::new(),
}
@@ -116,7 +145,7 @@ impl McpCredentials for SpyCredentials {
&self,
owner: &MacroUserIdStr<'static>,
destination: &McpDestination,
- ) -> Result<UpstreamCall, EgressError> {
+ ) -> Result<McpResolution, EgressError> {
let McpDestination::Connected(slug) = destination else {
unreachable!("these tests only dial connected servers");
};
@@ -125,15 +154,20 @@ impl McpCredentials for SpyCredentials {
.expect("lock")
.push((owner.to_string(), slug.to_string()));
- if !self.known {
+ if self.known == Knowledge::Unknown {
return Err(EgressError::UnknownServer(slug.clone()));
}
- Ok(UpstreamCall::bearer(
+ let call = UpstreamCall::bearer(
Url::parse(&self.url).expect("url"),
BearerToken::new("upstream-token"),
)?
- .scoped_by(self.scope.clone()))
+ .scoped_by(self.scope.clone());
+ Ok(match self.known {
+ Knowledge::Connected => McpResolution::Connected(call),
+ Knowledge::Unconnected => McpResolution::Unconnected(call),
+ Knowledge::Unknown => unreachable!("returned above"),
+ })
}
}
@@ -227,6 +261,250 @@ fn request(method: Method, header_pairs: &[(&str, &str)]) -> ProxyRequest {
request
}
+fn json_request(body: &str) -> ProxyRequest {
+ let mut request = http::Request::new(
+ Full::new(bytes::Bytes::from(body.to_owned()))
+ .map_err(|never| match never {})
+ .boxed_unsync(),
+ );
+ *request.method_mut() = Method::POST;
+ request
+}
+
+fn listing(slug: &str, name: &str) -> McpServerListing {
+ McpServerListing {
+ slug: McpServerSlug::parse(slug).expect("slug"),
+ name: name.to_owned(),
+ }
+}
+
+fn selected(listings: &[(&str, &str)]) -> Vec<McpServerListing> {
+ listings
+ .iter()
+ .map(|(slug, name)| listing(slug, name))
+ .collect()
+}
+
+async fn body_json(response: ProxyResponse) -> serde_json::Value {
+ let bytes = response
+ .into_body()
+ .collect()
+ .await
+ .expect("body")
+ .to_bytes();
+ serde_json::from_slice(&bytes).expect("json body")
+}
+
+/// An app the owner has not connected is still addressed for them: the
+/// handshake and listing go through whether or not the agent named the app,
+/// since every valid slug resolves against the owner's own connections.
+#[tokio::test]
+async fn an_unconnected_app_is_forwarded_even_when_the_agent_did_not_list_it() {
+ let service = EgressServiceImpl::new(
+ StubSessions::granting(),
+ SpyCredentials::unconnected(),
+ SpyGithubTokens::default(),
+ SpyForwarder::answering(&[]),
+ );
+
+ let response = service
+ .proxy(
+ &SessionToken::new("token"),
+ datadog(),
+ json_request(r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#),
+ )
+ .await
+ .expect("forwarded");
+
+ assert_eq!(response.status(), StatusCode::ACCEPTED);
+ assert!(service.forward.was_called());
+}
+
+/// With no name from the agent, the refusal calls the app by its slug made
+/// readable, so the person sees "Google Sheets" rather than "google_sheets".
+#[tokio::test]
+async fn an_unlisted_unconnected_app_is_named_from_its_slug() {
+ let service = EgressServiceImpl::new(
+ StubSessions::granting(),
+ SpyCredentials::unconnected(),
+ SpyGithubTokens::default(),
+ SpyForwarder::answering(&[]),
+ );
+ let sheets = EgressTarget::McpServer(McpDestination::Connected(
+ McpServerSlug::parse("google_sheets").expect("slug"),
+ ));
+
+ let response = service
+ .proxy(
+ &SessionToken::new("token"),
+ sheets,
+ json_request(r#"{"jsonrpc":"2.0","id":1,"method":"tools/call"}"#),
+ )
+ .await
+ .expect("answered");
+
+ let body = body_json(response).await;
+ let text = body["result"]["content"][0]["text"]
+ .as_str()
+ .expect("a text content block");
+ assert!(text.contains("Google Sheets is not connected"), "{text}");
+ assert!(
+ text.contains(
+ r#"<m-connect-app>{"appSlug":"google_sheets","name":"Google Sheets"}</m-connect-app>"#
+ ),
+ "{text}"
+ );
+}
+
+/// A listed app the owner has connected proxies exactly like before.
+#[tokio::test]
+async fn a_listed_connected_app_is_forwarded() {
+ let service = EgressServiceImpl::new(
+ StubSessions::granting_with(selected(&[("datadog", "Datadog")])),
+ SpyCredentials::knowing(),
+ SpyGithubTokens::default(),
+ SpyForwarder::answering(&[]),
+ );
+
+ let response = service
+ .proxy(
+ &SessionToken::new("token"),
+ datadog(),
+ json_request(r#"{"jsonrpc":"2.0","id":1,"method":"tools/call"}"#),
+ )
+ .await
+ .expect("proxied");
+
+ assert_eq!(response.status(), StatusCode::ACCEPTED);
+ assert!(service.forward.was_called());
+}
+
+/// A `tools/call` to an app the owner has not connected is answered by the
+/// proxy as the tool's own result, under the name the agent gave the app: the
+/// model reads that the app is not connected and how to get it connected,
+/// and nothing reaches the upstream.
+#[tokio::test]
+async fn a_tools_call_to_an_unconnected_app_is_answered_locally() {
+ let service = EgressServiceImpl::new(
+ StubSessions::granting_with(selected(&[("datadog", "Datadog")])),
+ SpyCredentials::unconnected(),
+ SpyGithubTokens::default(),
+ SpyForwarder::answering(&[]),
+ );
+
+ let response = service
+ .proxy(
+ &SessionToken::new("token"),
+ datadog(),
+ json_request(
+ r#"{"jsonrpc":"2.0","id":"call-7","method":"tools/call","params":{"name":"list_monitors","arguments":{"secret":"do-not-echo"}}}"#,
+ ),
+ )
+ .await
+ .expect("answered");
+
+ assert!(!service.forward.was_called());
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ response.headers()[http::header::CONTENT_TYPE],
+ "application/json"
+ );
+ let body = body_json(response).await;
+ assert_eq!(body["jsonrpc"], "2.0");
+ assert_eq!(body["id"], "call-7");
+ assert_eq!(body["result"]["isError"], true);
+ let text = body["result"]["content"][0]["text"]
+ .as_str()
+ .expect("a text content block");
+ assert!(text.contains("Datadog is not connected"), "{text}");
+ assert!(
+ text.contains(r#"<m-connect-app>{"appSlug":"datadog","name":"Datadog"}</m-connect-app>"#),
+ "{text}"
+ );
+ assert!(
+ text.contains("let you know once they have connected Datadog"),
+ "{text}"
+ );
+ assert!(!text.contains("do-not-echo"), "{text}");
+ assert!(!text.contains("list_monitors"), "{text}");
+}
+
+/// Everything but `tools/call` goes through for an unconnected app,
+/// addressed for the owner, so the client's handshake and tool listing work
+/// from the first turn; the body it read is put back intact.
+#[tokio::test]
+async fn the_handshake_and_listing_of_an_unconnected_app_are_forwarded() {
+ for (method, body) in [
+ (
+ Method::POST,
+ Some(r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#),
+ ),
+ (
+ Method::POST,
+ Some(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#),
+ ),
+ (
+ Method::POST,
+ Some(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#),
+ ),
+ (Method::GET, None),
+ (Method::DELETE, None),
+ ] {
+ let service = EgressServiceImpl::new(
+ StubSessions::granting_with(selected(&[("datadog", "Datadog")])),
+ SpyCredentials::unconnected(),
+ SpyGithubTokens::default(),
+ SpyForwarder::answering(&[]),
+ );
+ let request = match body {
+ Some(body) => json_request(body),
+ None => request(method.clone(), &[]),
+ };
+
+ let response = service
+ .proxy(&SessionToken::new("token"), datadog(), request)
+ .await
+ .expect("forwarded");
+
+ assert_eq!(response.status(), StatusCode::ACCEPTED, "{method} {body:?}");
+ assert!(service.forward.was_called(), "{method} {body:?}");
+ service.forward.forwarded(|parts| {
+ assert_eq!(parts.method, method);
+ assert_eq!(
+ parts
+ .headers
+ .get("x-pd-external-user-id")
+ .map(|value| value.to_str().expect("ascii")),
+ Some("owner"),
+ "{method} {body:?}: the owner's scoping is stamped on"
+ );
+ });
+ }
+}
+
+/// The one path that reads a request body is bounded.
+#[tokio::test]
+async fn an_oversized_request_to_an_unconnected_app_is_refused() {
+ let service = EgressServiceImpl::new(
+ StubSessions::granting_with(selected(&[("datadog", "Datadog")])),
+ SpyCredentials::unconnected(),
+ SpyGithubTokens::default(),
+ SpyForwarder::answering(&[]),
+ );
+ let huge = format!(
+ r#"{{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{{"pad":"{}"}}}}"#,
+ "x".repeat(crate::domain::model::MAX_MCP_REQUEST_BYTES)
+ );
+
+ let error = service
+ .proxy(&SessionToken::new("token"), datadog(), json_request(&huge))
+ .await
+ .expect_err("refused");
+
+ assert!(matches!(error, EgressError::RequestTooLarge));
+ assert!(!service.forward.was_called());
+}
+
fn datadog() -> EgressTarget {
EgressTarget::McpServer(McpDestination::Connected(
McpServerSlug::parse("datadog").expect("slug"),
@@ -400,6 +678,7 @@ async fn a_session_owned_outside_macro_gets_nothing() {
session: AgentSessionId::new(),
owner: MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),
repo: session_repo(),
+ mcp_servers: Vec::new(),
})),
SpyCredentials::knowing(),
SpyGithubTokens::default(),
diff --git a/crates/agent_egress/src/inbound/axum_router.rs b/crates/agent_egress/src/inbound/axum_router.rs
index fbd9039a7f..c95fb42f06 100644
--- a/crates/agent_egress/src/inbound/axum_router.rs
+++ b/crates/agent_egress/src/inbound/axum_router.rs
@@ -247,6 +247,7 @@ impl IntoResponse for EgressError {
Self::UnknownServer(_) | Self::Unroutable(_) => StatusCode::NOT_FOUND,
Self::RepoUnavailable(_) => StatusCode::FORBIDDEN,
Self::MethodNotAllowed(_) => StatusCode::METHOD_NOT_ALLOWED,
+ Self::RequestTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
// The named upstream is unusable as configured. Someone has to
// fix the URL; the agent cannot.
Self::InsecureUpstream(_) => StatusCode::BAD_GATEWAY,
@@ -271,6 +272,7 @@ impl IntoResponse for EgressError {
"This session's repository is not reachable with Macro's GitHub App."
}
Self::MethodNotAllowed(_) => "That method is not allowed here.",
+ Self::RequestTooLarge => "That request body is too large.",
Self::InsecureUpstream(_) => "That upstream is misconfigured and cannot be reached.",
Self::Upstream(_) => "The upstream could not be reached.",
Self::Internal(_) => "Egress failed.",
diff --git a/crates/agent_egress/src/inbound/axum_router/test.rs b/crates/agent_egress/src/inbound/axum_router/test.rs
index 24c50d35a9..c6a852b389 100644
--- a/crates/agent_egress/src/inbound/axum_router/test.rs
+++ b/crates/agent_egress/src/inbound/axum_router/test.rs
@@ -75,6 +75,7 @@ impl EgressService for SpyService {
Err(EgressError::MethodNotAllowed(method.clone()))
}
Some(EgressError::SessionClosed) => Err(EgressError::SessionClosed),
+ Some(EgressError::RequestTooLarge) => Err(EgressError::RequestTooLarge),
Some(EgressError::Upstream(_)) => {
Err(EgressError::Upstream(rootcause::report!("unreachable")))
}
@@ -211,6 +212,7 @@ async fn maps_each_refusal_to_the_status_that_tells_the_agent_what_to_do() {
EgressError::Upstream(rootcause::report!("nope")),
StatusCode::BAD_GATEWAY,
),
+ (EgressError::RequestTooLarge, StatusCode::PAYLOAD_TOO_LARGE),
] {
let service = SpyService::refusing(error);
let response = call(&service, get("/mcp/datadog", Some("Bearer session"))).await;
diff --git a/crates/agent_egress/src/outbound/macro_mcp.rs b/crates/agent_egress/src/outbound/macro_mcp.rs
index 6c1d2dedca..8413fe3f39 100644
--- a/crates/agent_egress/src/outbound/macro_mcp.rs
+++ b/crates/agent_egress/src/outbound/macro_mcp.rs
@@ -22,7 +22,7 @@ use std::sync::Mutex;
use url::Url;
use crate::domain::error::EgressError;
-use crate::domain::model::{BearerToken, McpDestination, UpstreamCall};
+use crate::domain::model::{BearerToken, McpDestination, McpResolution, UpstreamCall};
use crate::domain::ports::McpCredentials;
#[cfg(test)]
@@ -150,20 +150,19 @@ where
&self,
owner: &MacroUserIdStr<'static>,
destination: &McpDestination,
- ) -> Result<UpstreamCall, EgressError> {
+ ) -> Result<McpResolution, EgressError> {
if *destination != McpDestination::Macro {
return self.inner.resolve(owner, destination).await;
}
let token = BearerToken::new(self.token(owner).await?);
- if self.local_cleartext && self.url.scheme() != "https" {
- Ok(UpstreamCall::bearer_over_local_cleartext(
- self.url.clone(),
- token,
- ))
+ // Every session has Macro's own server; there is no grant to lack.
+ let call = if self.local_cleartext && self.url.scheme() != "https" {
+ UpstreamCall::bearer_over_local_cleartext(self.url.clone(), token)
} else {
- UpstreamCall::bearer(self.url.clone(), token)
- }
+ UpstreamCall::bearer(self.url.clone(), token)?
+ };
+ Ok(McpResolution::Connected(call))
}
}
diff --git a/crates/agent_egress/src/outbound/macro_mcp/test.rs b/crates/agent_egress/src/outbound/macro_mcp/test.rs
index 8cb4e88557..c1489035fb 100644
--- a/crates/agent_egress/src/outbound/macro_mcp/test.rs
+++ b/crates/agent_egress/src/outbound/macro_mcp/test.rs
@@ -64,7 +64,7 @@ impl McpCredentials for &SpyInner {
&self,
_owner: &MacroUserIdStr<'static>,
destination: &McpDestination,
- ) -> Result<UpstreamCall, EgressError> {
+ ) -> Result<McpResolution, EgressError> {
let McpDestination::Connected(slug) = destination else {
unreachable!("the decorator answers Macro's own destination itself");
};
@@ -83,10 +83,13 @@ async fn answers_macros_own_destination_with_a_minted_token() {
let inner = SpyInner::default();
let credentials = WithMacroMcp::new(&inner, &tokens, macro_url(), false).expect("constructed");
- let call = credentials
+ let McpResolution::Connected(call) = credentials
.resolve(&owner(), &McpDestination::Macro)
.await
- .expect("resolved");
+ .expect("resolved")
+ else {
+ panic!("Macro's own server is always connected");
+ };
assert_eq!(call.url().as_str(), "https://mcp.macro.com/mcp");
assert!(
@@ -160,10 +163,13 @@ async fn refuses_a_cleartext_url_unless_local_dev_permits_it() {
let inner = SpyInner::default();
let permitted = WithMacroMcp::new(&inner, &tokens, url, true).expect("constructed");
- let call = permitted
+ let McpResolution::Connected(call) = permitted
.resolve(&owner(), &McpDestination::Macro)
.await
- .expect("resolved");
+ .expect("resolved")
+ else {
+ panic!("Macro's own server is always connected");
+ };
assert_eq!(call.url().as_str(), "http://mcp-service:8080/mcp");
}
diff --git a/crates/agent_egress/src/outbound/mcp_credentials.rs b/crates/agent_egress/src/outbound/mcp_credentials.rs
index b616b6869c..2e65965d46 100644
--- a/crates/agent_egress/src/outbound/mcp_credentials.rs
+++ b/crates/agent_egress/src/outbound/mcp_credentials.rs
@@ -21,7 +21,9 @@ use pipedream_mcp::outbound::api::McpUpstream;
use std::sync::Arc;
use crate::domain::error::EgressError;
-use crate::domain::model::{BearerToken, McpDestination, McpServerSlug, UpstreamCall};
+use crate::domain::model::{
+ BearerToken, McpDestination, McpResolution, McpServerSlug, UpstreamCall,
+};
use crate::domain::ports::McpCredentials;
#[cfg(test)]
@@ -47,7 +49,8 @@ where
}
}
- /// The owner's enabled connection whose `app_slug` is exactly `slug`.
+ /// The owner's enabled connection whose `app_slug` is exactly `slug`, if
+ /// they hold one.
///
/// Scoped to the owner by the store call itself, and filtered to `enabled`
/// here because the store does not: a disabled connector is one the owner
@@ -56,8 +59,9 @@ where
&self,
owner: &MacroUserIdStr<'static>,
slug: &McpServerSlug,
- ) -> Result<PipedreamConnection, EgressError> {
- self.connections
+ ) -> Result<Option<PipedreamConnection>, EgressError> {
+ Ok(self
+ .connections
.list(owner)
.await
.map_err(|error| {
@@ -71,8 +75,7 @@ where
// stable identifier, and the display name is the user's to
// rename. The provisioner advertises the same value, and equality
// is the whole match - nothing is derived at either end.
- .find(|record| record.app_slug == slug.as_str())
- .ok_or_else(|| EgressError::UnknownServer(slug.clone()))
+ .find(|record| record.app_slug == slug.as_str()))
}
}
@@ -86,7 +89,7 @@ where
&self,
owner: &MacroUserIdStr<'static>,
destination: &McpDestination,
- ) -> Result<UpstreamCall, EgressError> {
+ ) -> Result<McpResolution, EgressError> {
// Macro's own server is the composition root's to layer on with
// [`crate::outbound::macro_mcp::WithMacroMcp`]; these rows can never
// answer for it.
@@ -96,7 +99,24 @@ where
the composition root did not layer WithMacroMcp"
)));
};
- let record = self.connection(owner, slug).await?;
+ // Pipedream addresses a call by user id and app slug alone (see
+ // `McpUpstream::upstream`), so an app the owner never connected is
+ // still addressable for them: the handshake and tool listing work,
+ // and only a call needs the grant. Reported as such, and the service
+ // decides what the session's policy makes of it.
+ let (record, connected) = match self.connection(owner, slug).await? {
+ Some(record) => (record, true),
+ None => (
+ PipedreamConnection {
+ user_id: owner.clone(),
+ app_slug: slug.as_str().to_owned(),
+ server_name: slug.as_str().to_owned(),
+ account_id: String::new(),
+ enabled: false,
+ },
+ false,
+ ),
+ };
// A dead grant is Pipedream's to notice, not ours: we hold no
// refresh token to fail on. If the account behind this connection has
@@ -111,9 +131,12 @@ where
// Typed at the source, but not yet vetted: `UpstreamCall`'s
// constructor is what refuses a non-https endpoint, and it is the
// only way to pair this URL with a credential.
- Ok(
- UpstreamCall::bearer(call.url, BearerToken::new(call.bearer_token))?
- .scoped_by(call.headers),
- )
+ let call = UpstreamCall::bearer(call.url, BearerToken::new(call.bearer_token))?
+ .scoped_by(call.headers);
+ Ok(if connected {
+ McpResolution::Connected(call)
+ } else {
+ McpResolution::Unconnected(call)
+ })
}
}
diff --git a/crates/agent_egress/src/outbound/mcp_credentials/test.rs b/crates/agent_egress/src/outbound/mcp_credentials/test.rs
index 07bd96dbaa..36f6cd6bca 100644
--- a/crates/agent_egress/src/outbound/mcp_credentials/test.rs
+++ b/crates/agent_egress/src/outbound/mcp_credentials/test.rs
@@ -1,5 +1,5 @@
use super::*;
-use crate::domain::model::McpDestination;
+use crate::domain::model::{McpDestination, McpResolution};
use http::header::{HeaderMap, HeaderValue};
use pipedream_mcp::outbound::api::McpUpstreamCall;
use std::sync::Mutex;
@@ -107,10 +107,13 @@ async fn resolves_an_app_slug_verbatim() {
upstream.clone(),
);
- let call = credentials
+ let McpResolution::Connected(call) = credentials
.resolve(&owner(), &connected("google_sheets"))
.await
- .expect("resolved");
+ .expect("resolved")
+ else {
+ panic!("a connected app resolves as connected");
+ };
assert_eq!(call.url().as_str(), "https://remote.mcp.pipedream.net/");
let asked = upstream.asked_for.lock().expect("spy lock");
@@ -126,10 +129,13 @@ async fn carries_the_scoping_headers_next_to_the_bearer() {
upstream.clone(),
);
- let call = credentials
+ let McpResolution::Connected(call) = credentials
.resolve(&owner(), &connected("linear"))
.await
- .expect("resolved");
+ .expect("resolved")
+ else {
+ panic!("a connected app resolves as connected");
+ };
let scope: Vec<(&str, &str)> = call
.scope_headers()
@@ -145,43 +151,62 @@ async fn carries_the_scoping_headers_next_to_the_bearer() {
);
}
+/// A disabled connection resolves like no connection: the owner turned the
+/// app off, and that takes the grant away from the sandbox. What remains is
+/// an addressable upstream with no grant behind it, which the service treats
+/// according to the session's policy.
#[tokio::test]
-async fn a_disabled_connection_is_an_unknown_server() {
+async fn a_disabled_connection_resolves_as_unconnected() {
let upstream = SpyUpstream::at("https://remote.mcp.pipedream.net");
let credentials = PipedreamMcpCredentials::new(
Arc::new(FixedConnections(vec![connection("linear", false)])),
upstream.clone(),
);
- let refusal = credentials
+ let resolution = credentials
.resolve(&owner(), &connected("linear"))
.await
- .expect_err("refused");
+ .expect("resolved");
assert!(
- matches!(refusal, EgressError::UnknownServer(_)),
- "{refusal}"
+ matches!(resolution, McpResolution::Unconnected(_)),
+ "{resolution:?}"
);
+ let asked = upstream.asked_for.lock().expect("spy lock");
+ assert_eq!(asked.len(), 1);
assert!(
- upstream.asked_for.lock().expect("spy lock").is_empty(),
- "a disabled connection must never reach Pipedream"
+ asked[0].account_id.is_empty(),
+ "the disabled row's account is not what gets addressed"
);
}
+/// An app nobody connected is still addressable for the owner - Pipedream
+/// scopes by user id and app slug alone - so it resolves as unconnected with
+/// exactly the owner's scoping, and no grant.
#[tokio::test]
-async fn a_slug_nobody_connected_is_an_unknown_server() {
+async fn a_slug_nobody_connected_resolves_as_unconnected_for_the_owner() {
let upstream = SpyUpstream::at("https://remote.mcp.pipedream.net");
let credentials =
PipedreamMcpCredentials::new(Arc::new(FixedConnections(Vec::new())), upstream.clone());
- let refusal = credentials
+ let McpResolution::Unconnected(call) = credentials
.resolve(&owner(), &connected("linear"))
.await
- .expect_err("refused");
+ .expect("resolved")
+ else {
+ panic!("an unconnected app resolves as unconnected");
+ };
+ let scope: Vec<(&str, &str)> = call
+ .scope_headers()
+ .iter()
+ .map(|(name, value)| (name.as_str(), value.to_str().expect("ascii")))
+ .collect();
+ assert!(scope.contains(&("x-pd-app-slug", "linear")), "{scope:?}");
+ let owner_id = owner().to_string();
assert!(
- matches!(refusal, EgressError::UnknownServer(_)),
- "{refusal}"
+ scope.contains(&("x-pd-external-user-id", owner_id.as_str())),
+ "{scope:?}"
);
}
diff --git a/crates/agent_egress/src/outbound/session_authority.rs b/crates/agent_egress/src/outbound/session_authority.rs
index a754d6af5d..bb2baad511 100644
--- a/crates/agent_egress/src/outbound/session_authority.rs
+++ b/crates/agent_egress/src/outbound/session_authority.rs
@@ -20,7 +20,7 @@ use agent_session::domain::model::SessionStatus;
use agent_session::domain::ports::AgentSessionRepo;
use crate::domain::error::EgressError;
-use crate::domain::model::{RepoSlug, SessionGrant, SessionToken};
+use crate::domain::model::{McpServerListing, McpServerSlug, RepoSlug, SessionGrant, SessionToken};
use crate::domain::ports::SessionAuthority;
/// Resolves a presented session token to its session by the digest stored
@@ -99,10 +99,29 @@ where
))
})?;
+ // The agent's own names for the apps it listed, off the row's
+ // snapshot, so a refusal can say "Google Sheets" rather than
+ // "google_sheets". Not a permission: any slug resolves against the
+ // owner's connections. A slug the strict parse refuses could never
+ // have been advertised, so skipping it changes nothing the sandbox
+ // can see.
+ let mcp_servers = session
+ .mcp_servers
+ .servers()
+ .iter()
+ .filter_map(|server| {
+ McpServerSlug::parse(&server.app_slug).map(|slug| McpServerListing {
+ slug,
+ name: server.server_name.clone(),
+ })
+ })
+ .collect();
+
Ok(SessionGrant {
session: session.id,
owner: session.owner_id,
repo,
+ mcp_servers,
})
}
}
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index 79b56f709d..30502c609b 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -3,7 +3,7 @@
use agent_client_protocol::schema::v1::{HttpHeader, McpServer as AcpMcpServer, McpServerHttp};
use agent_egress::domain::model::McpServerSlug;
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
-use agent_session::domain::model::{AgentSessionId, MessageId, SandboxSize};
+use agent_session::domain::model::{AgentMcpServers, AgentSessionId, MessageId, SandboxSize};
use agent_session::domain::ports::ControlEvent;
use bot_id::BotId;
use macro_user_id::user_id::MacroUserIdStr;
@@ -130,6 +130,8 @@ pub struct AgentRuntimeConfig {
pub harness: String,
/// Configured agent instructions, reserved for a dedicated runtime transport.
pub instructions: String,
+ /// Which Pipedream MCP servers the agent's sessions are handed.
+ pub mcp_servers: AgentMcpServers,
}
/// Whether a user belongs to the Macro staff domain - the egress crate's
@@ -344,9 +346,10 @@ pub struct SandboxEgress {
pub base_url: String,
/// The session token, presented on every proxied call.
pub session_token: String,
- /// The owner's connected MCP servers, by the slug the proxy resolves.
- /// Macro's own server is not listed: every session has it, on its own
- /// route.
+ /// The MCP servers to advertise, by the slug the proxy resolves: the
+ /// owner's connected apps, or the agent's selected apps whether or not
+ /// the owner has connected them. Macro's own server is not listed: every
+ /// session has it, on its own route.
pub mcp_servers: Vec<McpServerSlug>,
}
@@ -401,8 +404,7 @@ impl SandboxEgress {
}
/// Every server the session may dial, as `(name, url)` pairs: Macro's own
- /// server first, then the owner's connected apps under their Pipedream
- /// slugs.
+ /// server first, then the advertised apps under their Pipedream slugs.
///
/// The one enumeration behind both renderings - [`Self::acp_servers`] and
/// the Cursor API's - so the two can never advertise different sets.
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index 916d636145..33041993d8 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -5,7 +5,7 @@ use std::pin::Pin;
use std::sync::Arc;
use agent_session::domain::connection::RuntimeAttachment;
-use agent_session::domain::model::{AgentSessionId, SandboxSize};
+use agent_session::domain::model::{AgentMcpServers, AgentSessionId, SandboxSize};
use agent_session::domain::ports::AgentConnector;
use bot_id::BotId;
use harness_id::HarnessId;
@@ -184,23 +184,30 @@ pub trait RuntimeConnections: Send + Sync + 'static {
pub trait SandboxEgressProvisioner: Send + Sync + 'static {
/// The egress environment for one session, on behalf of `owner`, and the
/// hash its session row must carry for that environment to mean anything.
+ ///
+ /// `selection` is the session's MCP policy: under
+ /// [`AgentMcpServers::OwnerConnections`] the owner's enabled apps are
+ /// advertised; under [`AgentMcpServers::Selected`] exactly the listed
+ /// apps are, connected or not.
fn provision(
&self,
session: AgentSessionId,
owner: &MacroUserIdStr<'static>,
repo_url: &str,
+ selection: &AgentMcpServers,
) -> impl Future<Output = Result<ProvisionedEgress>> + Send;
/// The egress environment rebuilt around a token that already exists.
///
/// For reattaching to a sandbox that was spawned earlier: the sandbox
/// still holds its raw token (the row holds only the hash), so nothing is
- /// minted - but the owner's connected servers are listed fresh, so an app
+ /// minted - but the servers are listed fresh, so an app the owner
/// connected since the spawn is advertised on the next attach.
fn restore(
&self,
owner: &MacroUserIdStr<'static>,
session_token: String,
+ selection: &AgentMcpServers,
) -> impl Future<Output = Result<SandboxEgress>> + Send;
}
diff --git a/crates/agent_harness/src/domain/ports/test.rs b/crates/agent_harness/src/domain/ports/test.rs
index 9a7ec28780..fcc4956cf3 100644
--- a/crates/agent_harness/src/domain/ports/test.rs
+++ b/crates/agent_harness/src/domain/ports/test.rs
@@ -37,6 +37,7 @@ fn params(id: AgentSessionId) -> CreateAgentSessionParams {
workspace: "/workspace".to_owned(),
sandbox_size: agent_session::domain::model::SandboxSize::Default,
instructions: None,
+ mcp_servers: Default::default(),
egress_token_hash: None,
}
}
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index b6ff47a4ee..502938c027 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -1,6 +1,26 @@
+//! The orchestrator behind every agent session: one service over the ports
+//! in [`crate::domain::ports`], split by concern.
+//!
+//! - [`queue`]: the per-session command queue and its worker, the one-turn-
+//! in-flight invariant, and routing a command to whichever replica holds
+//! the session's actor.
+//! - [`open`]: creating sessions - from a mention, from the create menu, or
+//! for an external runtime - and provisioning their egress.
+//! - [`deliver`]: composing a queued action with channel context and handing
+//! it to the running agent, announcing it in the channel first.
+//! - [`lifecycle`]: everything after open - control events, sandbox size,
+//! turn boundaries, teardown.
+//!
+//! This file holds the service type itself and its public entry points.
+
#[cfg(test)]
mod test;
+mod deliver;
+mod lifecycle;
+mod open;
+mod queue;
+
use std::sync::Arc;
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
@@ -8,7 +28,8 @@ use agent_session::domain::connection::RuntimeAttachment;
use agent_session::domain::error::AgentSessionError;
use agent_session::domain::model::SessionManagement;
use agent_session::domain::model::{
- AgentSession, AgentSessionId, AuthorKind, CreateAgentSessionParams, MessageId, SandboxSize,
+ AgentMcpServers, AgentSession, AgentSessionId, AuthorKind, CreateAgentSessionParams, MessageId,
+ SandboxSize,
};
use agent_session::domain::ports::{
AcceptedControl, AgentSessionNotificationRecipient, AgentSessionQueueChanged,
@@ -35,46 +56,7 @@ use crate::domain::ports::{
use crate::domain::queue::{QueueError, QueuedEntry, SessionQueues};
use crate::domain::sandbox::SandboxResizeEffect;
-type SessionWorkers = DashMap<AgentSessionId, mpsc::UnboundedSender<QueuedCommand>>;
-
-struct QueuedCommand {
- command: HarnessCommand,
- completed: oneshot::Sender<Result<CommandOutcome>>,
- /// The caller's span, carried across the queue so the work the worker does
- /// on its own task still hangs off whatever triggered it.
- span: tracing::Span,
- /// Whether the worker resolves the session's managing replica before
- /// executing. Commands admitted at an ingress route; a command received
- /// *as* a forward executes here unconditionally, which is what makes
- /// forwarding single-hop - two replicas with momentarily different lease
- /// views cannot bounce a command between each other.
- route: bool,
-}
-
-/// [`CommandForwarder`], object-safe.
-///
-/// Held erased inside the service so forwarding does not become an eighth
-/// type parameter on every impl block; the public port keeps its natural
-/// `impl Future` shape and this shim boxes at the one internal call site.
-trait ErasedForwarder: Send + Sync + 'static {
- fn forward<'a>(
- &'a self,
- session: AgentSessionId,
- command: HarnessCommand,
- target: crate::domain::ports::CommandTarget,
- ) -> std::pin::Pin<Box<dyn Future<Output = Result<CommandOutcome>> + Send + 'a>>;
-}
-
-impl<F: CommandForwarder> ErasedForwarder for F {
- fn forward<'a>(
- &'a self,
- session: AgentSessionId,
- command: HarnessCommand,
- target: crate::domain::ports::CommandTarget,
- ) -> std::pin::Pin<Box<dyn Future<Output = Result<CommandOutcome>> + Send + 'a>> {
- Box::pin(CommandForwarder::forward(self, session, command, target))
- }
-}
+use self::queue::{ErasedForwarder, SessionWorkers};
struct AgentHarnessInner<
Sessions,
@@ -234,63 +216,6 @@ where
self.enqueue(session_id, command, false)
}
- fn enqueue(
- &self,
- session_id: AgentSessionId,
- mut command: HarnessCommand,
- route: bool,
- ) -> impl Future<Output = Result<CommandOutcome>> + Send + 'static {
- let caller = tracing::Span::current();
- let result = loop {
- let commands = self.commands(session_id);
- let (completed, result) = oneshot::channel();
- let queued = QueuedCommand {
- command,
- completed,
- span: caller.clone(),
- route,
- };
-
- match commands.send(queued) {
- Ok(()) => break result,
- Err(error) => {
- command = error.0.command;
- self.workers
- .remove_if(&session_id, |_, current| current.same_channel(&commands));
- }
- }
- };
-
- async move {
- result
- .await
- .map_err(|_| HarnessError::CommandWorkerStopped(session_id))?
- }
- }
-
- fn commands(&self, session_id: AgentSessionId) -> mpsc::UnboundedSender<QueuedCommand> {
- match self.workers.entry(session_id) {
- Entry::Occupied(entry) => entry.get().clone(),
- Entry::Vacant(entry) => {
- let (commands, receiver) = mpsc::unbounded_channel();
- entry.insert(commands.clone());
- self.spawn_worker(session_id, receiver);
- commands
- }
- }
- }
-
- fn spawn_worker(
- &self,
- session_id: AgentSessionId,
- receiver: mpsc::UnboundedReceiver<QueuedCommand>,
- ) {
- // The worker outlives the call that created it, so it has to carry the
- // subscriber forward itself or every command it runs traces nowhere.
- let inner = self.inner.clone();
- tokio::spawn(run_session_worker(session_id, inner, receiver).with_current_subscriber());
- }
-
/// Post the announcement for a prompt an external runtime delivers.
///
/// The follow-up-mention half of the external split: the runtime sends
@@ -377,383 +302,6 @@ where
}
}
-/// The harness is what holds a session's live resources, so it is what the
-/// control routes notify. Both operations go through the per-session queue, so
-/// a teardown cannot land in the middle of an open and a model change cannot
-/// overtake the prompt it was meant to follow.
-impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
- AgentSessionNotificationRecipient
- for AgentHarnessService<
- Sessions,
- Containers,
- Announcer,
- Runtimes,
- PromptContext,
- PromptComposer,
- Egress,
- >
-where
- Sessions: AgentSessionService,
- Containers: ContainerManager,
- Announcer: SessionAnnouncer,
- Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
- PromptComposer: AgentPromptComposer,
- Egress: SandboxEgressProvisioner,
-{
- async fn session_deleted(
- &self,
- id: AgentSessionId,
- ) -> agent_session::domain::error::Result<()> {
- self.execute(id, HarnessCommand::Delete)
- .await
- .map(drop)
- .map_err(into_session_error)
- }
-
- async fn control_event(
- &self,
- id: AgentSessionId,
- event: ControlEvent,
- ) -> agent_session::domain::error::Result<AcceptedControl> {
- let action_id = AgentActionId::mint();
- let outcome = self
- .execute(
- id,
- HarnessCommand::Deliver(DeliverAction::control(action_id, event)),
- )
- .await
- .map_err(into_session_error)?;
- Ok(AcceptedControl {
- action_id,
- disposition: match outcome {
- CommandOutcome::Completed => ControlDisposition::Sent,
- CommandOutcome::Queued => ControlDisposition::Queued,
- },
- })
- }
-
- /// A local read on purpose: the queue lives beside the session's live
- /// actor, and this replica answers for what it holds. A reader landing on
- /// a non-managing replica sees an empty queue rather than an error.
- async fn queued_controls(
- &self,
- id: AgentSessionId,
- ) -> agent_session::domain::error::Result<Vec<QueuedControl>> {
- Ok(self.inner.queues.list(id))
- }
-
- async fn edit_queued_control(
- &self,
- id: AgentSessionId,
- action_id: AgentActionId,
- prompt: String,
- actor: Option<MacroUserIdStr<'static>>,
- ) -> agent_session::domain::error::Result<()> {
- self.execute(
- id,
- HarnessCommand::EditQueued {
- action_id,
- prompt,
- actor,
- },
- )
- .await
- .map(drop)
- .map_err(into_session_error)
- }
-
- async fn remove_queued_control(
- &self,
- id: AgentSessionId,
- action_id: AgentActionId,
- actor: Option<MacroUserIdStr<'static>>,
- ) -> agent_session::domain::error::Result<()> {
- self.execute(id, HarnessCommand::RemoveQueued { action_id, actor })
- .await
- .map(drop)
- .map_err(into_session_error)
- }
-
- async fn set_sandbox_size(
- &self,
- id: AgentSessionId,
- size: SandboxSize,
- ) -> agent_session::domain::error::Result<()> {
- self.execute(id, HarnessCommand::SetSandboxSize(size))
- .await
- .map(drop)
- .map_err(into_session_error)
- }
-
- async fn session_harness(
- &self,
- id: AgentSessionId,
- ) -> agent_session::domain::error::Result<Option<harness_id::HarnessId>> {
- // The row is the source of truth for which bot the session runs, and
- // the binding resolves the bot's current harness the same way `bind`
- // does at delivery time.
- let session = self.inner.sessions.get_session(id).await?;
- self.inner
- .runtimes
- .bound_harness(session.bot_id)
- .await
- .map_err(AgentSessionError::Unknown)
- }
-}
-
-/// The queue drains on the session's own command worker, so both signals
-/// only admit an internal command there and return. Admission is synchronous
-/// inside [`AgentHarnessService::execute_here`]; the returned future only
-/// awaits the completion, which nothing here needs.
-impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
- agent_session::domain::ports::SessionTurnObserver
- for AgentHarnessService<
- Sessions,
- Containers,
- Announcer,
- Runtimes,
- PromptContext,
- PromptComposer,
- Egress,
- >
-where
- Sessions: AgentSessionService,
- Containers: ContainerManager,
- Announcer: SessionAnnouncer,
- Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
- PromptComposer: AgentPromptComposer,
- Egress: SandboxEgressProvisioner,
-{
- fn turn_ended(&self, id: AgentSessionId) {
- drop(self.execute_here(id, HarnessCommand::TurnEnded));
- }
-
- fn session_stopped(&self, id: AgentSessionId) {
- drop(self.execute_here(id, HarnessCommand::SessionStopped));
- }
-}
-
-/// External sessions create the row and announce - the magic-chip message
-/// the session's bot posts into the mention's thread, which is where the
-/// app renders the session's replies. No sandbox (the runtime dials in) and
-/// no first prompt (the runtime sends it through the control endpoint).
-/// The announcement is best-effort: a session a runtime is about to serve
-/// must not die because the courtesy post failed, most plainly when the bot
-/// cannot post in the claimed channel.
-impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
- agent_session::domain::ports::SessionOpener
- for AgentHarnessService<
- Sessions,
- Containers,
- Announcer,
- Runtimes,
- PromptContext,
- PromptComposer,
- Egress,
- >
-where
- Sessions: AgentSessionService,
- Containers: ContainerManager,
- Announcer: SessionAnnouncer,
- Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
- PromptComposer: AgentPromptComposer,
- Egress: SandboxEgressProvisioner,
-{
- async fn open_external_session(
- &self,
- request: agent_session::domain::ports::OpenExternalAgentSession,
- ) -> agent_session::domain::error::Result<AgentSession> {
- let defaults = self.inner.defaults.for_bot(request.bot_id);
- let session = self
- .inner
- .sessions
- .create_session(CreateAgentSessionParams {
- id: AgentSessionId::new(),
- owner_id: request.owner.clone(),
- bot_id: request.bot_id,
- thread_id: request.thread.as_ref().map(|thread| thread.thread_id),
- originating_message_id: request.thread.as_ref().map(|thread| thread.message_id),
- model: defaults.model.clone(),
- harness: defaults.harness.clone(),
- repo_url: request.repo_url,
- workspace: request.workspace,
- sandbox_size: SandboxSize::Default,
- instructions: request.instructions,
- // No sandbox: the runtime dials in and reaches the network on
- // its operator's own terms, so there is no egress token.
- egress_token_hash: None,
- // The thread linkage is the caller's claim, not an observed
- // mention; it must not grant the channel anything.
- })
- .await?;
-
- if let Some(thread) = request.thread {
- let announcement = SessionAnnouncement {
- session_id: session.id,
- bot_id: request.bot_id,
- origin_channel_id: thread.channel_id,
- origin_thread_id: thread.thread_id,
- origin_message_id: thread.message_id,
- prompted_message_id: MessageId::first(AuthorKind::User),
- prompted_content: thread.content,
- triggered_by: request.owner,
- };
- if let Err(error) = self.inner.announcer.announce(announcement).await {
- tracing::warn!(
- error = ?error,
- session = %session.id,
- "external session announcement failed; the session runs unannounced"
- );
- }
- }
-
- Ok(session)
- }
-
- /// Provision the managed-default bot's runtime, open a session on it,
- /// and deliver the first prompt if one came with the request.
- ///
- /// Nothing is announced: a managed session opened this way has no
- /// originating mention and no thread to answer back into. The runtime is
- /// spawned before the session is attached because there is nothing to
- /// attach to until it exists.
- async fn open_managed_session(
- &self,
- request: agent_session::domain::ports::OpenManagedSession,
- ) -> agent_session::domain::error::Result<AgentSession> {
- let defaults = self.inner.defaults.managed();
- let sandbox_size = self
- .inner
- .sessions
- .user_sandbox_size(&request.owner)
- .await?;
- let session_id = AgentSessionId::new();
- // Same ordering as the trigger path's open: the token has to be minted
- // before the row, because the row is what carries the hash that makes
- // it mean anything.
- let egress = self
- .inner
- .egress
- .provision(session_id, &request.owner, &defaults.repo_url)
- .await
- .map_err(into_session_error)?;
- let session = self
- .inner
- .sessions
- .create_session(CreateAgentSessionParams {
- id: session_id,
- owner_id: request.owner.clone(),
- bot_id: defaults.bot_id,
- thread_id: None,
- originating_message_id: None,
- model: defaults.model.clone(),
- harness: defaults.harness.clone(),
- repo_url: Some(defaults.repo_url.clone()),
- // Managed sandboxes run in the path baked into their image.
- workspace: agent_session::MANAGED_CONTAINER_WORKSPACE.to_owned(),
- sandbox_size,
- instructions: request.instructions,
- egress_token_hash: Some(egress.session_token_hash),
- })
- .await?;
-
- let mcp_servers = egress.sandbox.acp_servers();
- let container = match self
- .inner
- .containers
- .spawn(SpawnContainer {
- session_id: session.id,
- kind: AgentKind::for_session(session.bot_id, &session.harness),
- size: sandbox_size,
- egress: egress.sandbox,
- })
- .await
- {
- Ok(container) => container,
- // The row is already persisted, so a sandbox that never arrived
- // would otherwise leave a session claiming to be live. Same
- // handling as the trigger path's open.
- Err(error) => {
- let _ = self
- .inner
- .sessions
- .mark_disconnected(session.id)
- .await
- .inspect_err(|status_error| {
- tracing::error!(
- error = ?status_error,
- session_id = %session.id,
- "failed to mark an unprovisioned session disconnected"
- );
- });
- return Err(into_session_error(error));
- }
- };
- self.inner
- .sessions
- .attach_session(
- session.id,
- RuntimeAttachment::solo(container).mcp_servers(mcp_servers),
- )
- .await?;
-
- // Raw, through the session's own command worker: dispatch is where a
- // prompt is composed, and the worker is what serializes this first
- // prompt against any control prompt racing the session's birth.
- if let Some(raw_prompt) = request.prompt {
- self.execute_here(
- session.id,
- HarnessCommand::Deliver(DeliverAction {
- id: AgentActionId::mint(),
- action: AgentAction::prompt(raw_prompt),
- actor: Some(request.owner),
- announce: None,
- }),
- )
- .await
- .map_err(into_session_error)?;
- }
-
- Ok(session)
- }
-
- async fn find_thread_session(
- &self,
- thread_id: macro_uuid::Uuid,
- bot_id: BotId,
- ) -> agent_session::domain::error::Result<Option<AgentSessionId>> {
- match self
- .inner
- .sessions
- .find_for_channel(Some(thread_id), Some(bot_id))
- .await?
- {
- agent_session::domain::model::ChannelSession::CreatedFromThread(session) => {
- Ok(Some(session.id))
- }
- agent_session::domain::model::ChannelSession::None => Ok(None),
- }
- }
-}
-
-/// Map a queue refusal into the session vocabulary, which is where the
-/// control surface's callers read their errors from.
-fn queue_result<T>(
- result: std::result::Result<T, QueueError>,
- session_id: AgentSessionId,
-) -> Result<T> {
- result.map_err(|error| {
- HarnessError::Session(match error {
- QueueError::NotFound => AgentSessionError::QueuedControlNotFound,
- QueueError::NotEditable => AgentSessionError::QueuedControlNotEditable,
- QueueError::Full => AgentSessionError::ControlQueueFull(session_id),
- })
- })
-}
-
/// Collapse a harness failure back into the session vocabulary the port speaks.
///
/// A harness error that started life as a session error is unwrapped rather
@@ -765,740 +313,3 @@ fn into_session_error(error: HarnessError) -> AgentSessionError {
other => AgentSessionError::Unknown(anyhow::anyhow!(other)),
}
}
-
-impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
- AgentHarnessInner<
- Sessions,
- Containers,
- Announcer,
- Runtimes,
- PromptContext,
- PromptComposer,
- Egress,
- >
-where
- Sessions: AgentSessionService,
- Containers: ContainerManager,
- Announcer: SessionAnnouncer,
- Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
- PromptComposer: AgentPromptComposer,
- Egress: SandboxEgressProvisioner,
-{
- /// Execute where the session's live actor is: locally when nobody (or
- /// this replica) manages it, on the managing peer otherwise.
- /// The routing decision is recorded on the span, not only logged: which of
- /// the three answers the lease gave, which peer it named, and whether the
- /// command left this process. Those are the fields you group by when a
- /// replica is mishandling commands, and a log line cannot be aggregated.
- #[tracing::instrument(
- err,
- skip(self, command),
- fields(
- %session_id,
- agent.session.management = tracing::field::Empty,
- agent.session.manager_replica = tracing::field::Empty,
- agent.command.forwarded = tracing::field::Empty,
- )
- )]
- async fn route_then_execute(
- &self,
- session_id: AgentSessionId,
- command: HarnessCommand,
- ) -> Result<CommandOutcome> {
- let span = tracing::Span::current();
- // Open never routes: it is what creates the session row this routing
- // would read, and a fresh id has no manager to defer to.
- if matches!(command, HarnessCommand::Open(_)) {
- span.record("agent.session.management", "open");
- span.record("agent.command.forwarded", false);
- return self.execute(session_id, command).await;
- }
- let manager = match self.sessions.management(session_id).await? {
- SessionManagement::Unmanaged => {
- span.record("agent.session.management", "unmanaged");
- span.record("agent.command.forwarded", false);
- let session = self.sessions.get_session(session_id).await?;
- if AgentKind::for_session(session.bot_id, &session.harness) != AgentKind::External {
- return self.execute(session_id, command).await;
- }
- let Some(harness) = self
- .runtimes
- .bound_harness(session.bot_id)
- .await
- .map_err(AgentSessionError::Unknown)?
- else {
- return self.execute(session_id, command).await;
- };
- if self.runtimes.is_connected(harness) {
- return self.execute(session_id, command).await;
- }
- span.record("agent.command.forwarded", true);
- return self
- .forwarder
- .forward(
- session_id,
- command,
- crate::domain::ports::CommandTarget::Harness(harness),
- )
- .await;
- }
- SessionManagement::Ours => {
- span.record("agent.session.management", "ours");
- span.record("agent.command.forwarded", false);
- return self.execute(session_id, command).await;
- }
- SessionManagement::Peer(manager) => manager,
- };
- span.record("agent.session.management", "peer");
- span.record(
- "agent.session.manager_replica",
- tracing::field::display(manager.replica),
- );
- span.record("agent.command.forwarded", true);
- tracing::info!(%session_id, peer = %manager.replica, "forwarding an agent session command");
- self.forwarder
- .forward(
- session_id,
- command,
- crate::domain::ports::CommandTarget::Replica(manager.replica),
- )
- .await
- }
-
- async fn execute(
- &self,
- session_id: AgentSessionId,
- command: HarnessCommand,
- ) -> Result<CommandOutcome> {
- match &command {
- HarnessCommand::Open(open)
- if AgentKind::of(open.bot_id) == AgentKind::SandboxedCoder
- && !is_macro_staff(&open.origin.sender) =>
- {
- return Err(AgentSessionError::Forbidden.into());
- }
- // The queue mutations sit behind the same staff gate as delivery:
- // an edited entry is delivered later under its original identity,
- // so rewriting (or dropping) what a Daytona session is about to
- // run is the same privilege as prompting it.
- HarnessCommand::Deliver(DeliverAction { actor, .. })
- | HarnessCommand::EditQueued { actor, .. }
- | HarnessCommand::RemoveQueued { actor, .. } => {
- let session = self.sessions.get_session(session_id).await?;
- if AgentKind::of(session.bot_id) == AgentKind::SandboxedCoder
- && !actor.as_ref().is_some_and(is_macro_staff)
- {
- return Err(AgentSessionError::Forbidden.into());
- }
- }
- HarnessCommand::Open(_)
- | HarnessCommand::TurnEnded
- | HarnessCommand::SessionStopped
- | HarnessCommand::SetSandboxSize(_)
- | HarnessCommand::Delete => {}
- }
-
- match command {
- HarnessCommand::Open(command) => {
- self.open(session_id, command).await?;
- Ok(CommandOutcome::Completed)
- }
- // Turn-occupying actions go through the queue - the running
- // turn's end is what dispatches them. Everything else delivers
- // now: a stop rides alongside the turn it cancels, and that
- // turn's cancelled answer is an ordinary turn end.
- HarnessCommand::Deliver(command) if command.action.occupies_turn() => {
- self.enqueue_then_dispatch(session_id, command).await
- }
- HarnessCommand::Deliver(command) => {
- self.deliver(session_id, command).await?;
- Ok(CommandOutcome::Completed)
- }
- HarnessCommand::EditQueued {
- action_id,
- prompt,
- actor,
- } => {
- queue_result(
- self.queues
- .edit_prompt(session_id, action_id, prompt, actor),
- session_id,
- )?;
- self.publish_queue(session_id).await;
- Ok(CommandOutcome::Completed)
- }
- HarnessCommand::RemoveQueued { action_id, .. } => {
- queue_result(self.queues.remove(session_id, action_id), session_id)?;
- self.publish_queue(session_id).await;
- Ok(CommandOutcome::Completed)
- }
- HarnessCommand::TurnEnded => {
- self.busy.remove(&session_id);
- let dispatched = self.dispatch_next(session_id).await;
- // Published whatever dispatching did: a claim, a requeued
- // failure, and an emptied queue are all changes a viewer is
- // watching for.
- self.publish_queue(session_id).await;
- dispatched?;
- Ok(CommandOutcome::Completed)
- }
- HarnessCommand::SessionStopped => {
- self.busy.remove(&session_id);
- Ok(CommandOutcome::Completed)
- }
- HarnessCommand::SetSandboxSize(size) => {
- self.apply_sandbox_size(session_id, size).await?;
- Ok(CommandOutcome::Completed)
- }
- HarnessCommand::Delete => {
- self.delete(session_id).await?;
- // The queue and busy mark die with the session: a deleted
- // session's entries will never dispatch, and leaving them
- // would leak them for the life of the process. The published
- // empty snapshot is the viewers' goodbye.
- self.busy.remove(&session_id);
- self.queues.drop_session(session_id);
- self.publish_queue(session_id).await;
- Ok(CommandOutcome::Completed)
- }
- }
- }
-
- /// Queue a turn-occupying action, and dispatch the head of the queue
- /// right away when no turn is running.
- ///
- /// The dispatched entry is usually the one just queued, but not
- /// necessarily: entries can linger from a drain that failed, and FIFO
- /// order holds regardless. The outcome reports what happened to *this*
- /// action - still waiting, or on the wire.
- async fn enqueue_then_dispatch(
- &self,
- session_id: AgentSessionId,
- command: DeliverAction,
- ) -> Result<CommandOutcome> {
- let action_id = command.id;
- queue_result(
- self.queues.enqueue(
- session_id,
- QueuedEntry {
- action_id,
- action: command.action,
- actor: command.actor,
- announce: command.announce,
- announced: false,
- created_at: chrono::Utc::now(),
- },
- ),
- session_id,
- )?;
-
- let dispatched = if self.busy.contains_key(&session_id) {
- Ok(())
- } else {
- self.dispatch_next(session_id).await
- };
- self.publish_queue(session_id).await;
- dispatched?;
-
- Ok(if self.queues.contains(session_id, action_id) {
- CommandOutcome::Queued
- } else {
- CommandOutcome::Completed
- })
- }
-
- /// Push the queue as it now stands to the session's viewers.
- ///
- /// Best-effort, like every realtime publish: a dropped snapshot costs a
- /// viewer liveness until the next change, and the queue itself is intact -
- /// so this logs and never fails the command it rides on.
- async fn publish_queue(&self, session_id: AgentSessionId) {
- let _ = self
- .sessions
- .publish_queue_changed(AgentSessionQueueChanged {
- agent_session_id: session_id,
- entries: self.queues.list(session_id),
- })
- .await
- .inspect_err(|error| {
- tracing::warn!(
- error = ?error,
- %session_id,
- "failed to publish an agent session queue change"
- );
- });
- }
-
- /// Deliver the oldest queued action, marking the session busy on success.
- ///
- /// Composition runs first so a lexical failure never posts a chip for a
- /// prompt that will not reach the agent. The chip is then announced
- /// (from the raw text) before delivery, so it exists to anchor the turn
- /// the agent streams into - and it is announced *at most once* per
- /// entry: the claimed entry remembers a successful announce, so a
- /// dispatch that fails after the chip posted retries without posting a
- /// second one.
- ///
- /// A failed dispatch puts the entry back at the front: it stays next in
- /// line for the next turn end or the next prompt, and stays visible in
- /// the queue meanwhile. The error still propagates, so a caller whose
- /// own action triggered this dispatch hears about it.
- #[tracing::instrument(err, skip(self), fields(%session_id))]
- async fn dispatch_next(&self, session_id: AgentSessionId) -> Result<()> {
- let Some(mut entry) = self.queues.claim_next(session_id) else {
- return Ok(());
- };
-
- // Compose a copy: the queued entry stays raw so a retry still edits
- // and re-composes the user's text, and the chip (below) still shows
- // what they typed rather than the composed payload.
- let mut composed = entry.action.clone();
- if let Err(error) = self
- .compose_action(&mut composed, entry.actor.as_ref(), entry.announce.as_ref())
- .await
- {
- self.queues.requeue_front(session_id, entry);
- return Err(error);
- }
-
- if !entry.announced {
- let announcement = match self
- .announcement(
- session_id,
- &entry.action,
- entry.actor.as_ref(),
- entry.announce.clone(),
- )
- .await
- {
- Ok(announcement) => announcement,
- Err(error) => {
- self.queues.requeue_front(session_id, entry);
- return Err(error);
- }
- };
- if let Some(announcement) = announcement {
- if let Err(error) = self.announcer.announce(announcement).await {
- self.queues.requeue_front(session_id, entry);
- return Err(error);
- }
- entry.announced = true;
- }
- }
-
- let command = DeliverAction {
- id: entry.action_id,
- action: composed,
- actor: entry.actor.clone(),
- announce: entry.announce.clone(),
- };
- match self.deliver(session_id, command).await {
- Ok(()) => {
- self.busy.insert(session_id, ());
- Ok(())
- }
- Err(error) => {
- self.queues.requeue_front(session_id, entry);
- Err(error)
- }
- }
- }
-
- /// The MCP servers to advertise when reattaching to an existing container.
- ///
- /// The raw session token exists in exactly one place after spawn - the
- /// container's own environment - so it is read back from there and wrapped
- /// in a fresh listing of the owner's connected servers. A container that
- /// holds no token (a provider whose sessions carry no egress environment,
- /// or a sandbox from before tokens existed) gets no servers, which is
- /// also everything it could do with them.
- #[tracing::instrument(err, skip(self, owner), fields(%session_id, %owner))]
- async fn resumed_mcp_servers(
- &self,
- session_id: AgentSessionId,
- owner: &MacroUserIdStr<'static>,
- ) -> Result<Vec<agent_client_protocol::schema::v1::McpServer>> {
- let Some(session_token) = self.containers.session_token(session_id).await? else {
- tracing::debug!("container holds no egress token; restoring no MCP servers");
- return Ok(Vec::new());
- };
- Ok(self
- .egress
- .restore(owner, session_token)
- .await?
- .acp_servers())
- }
-
- /// Release everything the session holds, then delete it.
- ///
- /// The durable delete goes last on purpose. Crashing between the two
- /// leaves a session whose container is gone, which `resume` heals by
- /// spawning a new one; the other order leaves a paid sandbox that nothing
- /// knows to reap.
- #[tracing::instrument(err, skip(self), fields(%session_id))]
- async fn delete(&self, session_id: AgentSessionId) -> Result<()> {
- self.sessions.close_session(session_id).await?;
- self.containers.teardown(session_id).await?;
- self.sessions.delete_session(session_id).await?;
- Ok(())
- }
-
- /// Apply `size` to this session's sandbox and remember it as the owner's default.
- ///
- /// The container manager reports whether the change is in-place, needs a
- /// stop, or is unsupported. Disk is never changed.
- #[tracing::instrument(err, skip(self), fields(%session_id, %size))]
- async fn apply_sandbox_size(
- &self,
- session_id: AgentSessionId,
- size: SandboxSize,
- ) -> Result<()> {
- let session = self.sessions.get_session(session_id).await?;
- let effect = self.containers.resize_effect(session.sandbox_size, size);
- // Only a sandboxed coder has a sandbox to act on: a Cursor session
- // runs in Cursor's cloud, the in-memory bot has no sandbox, and an
- // external bot provisions its own. For all three, the size is only
- // recorded below as a preference.
- if AgentKind::for_session(session.bot_id, &session.harness) == AgentKind::SandboxedCoder
- && effect != SandboxResizeEffect::NoOp
- {
- if effect == SandboxResizeEffect::Restart {
- self.sessions.close_session(session_id).await?;
- }
- self.containers.resize(session_id, size).await?;
- if effect == SandboxResizeEffect::Restart {
- let container = self.containers.resume(session_id).await?;
- let mcp_servers = self
- .resumed_mcp_servers(session_id, &session.owner_id)
- .await?;
- self.sessions
- .attach_session(
- session_id,
- RuntimeAttachment::solo(container).mcp_servers(mcp_servers),
- )
- .await?;
- }
- }
- self.sessions.set_sandbox_size(session_id, size).await?;
- self.sessions
- .set_user_sandbox_size(&session.owner_id, size)
- .await?;
- Ok(())
- }
-
- #[tracing::instrument(err, skip(self, command), fields(
- %session_id,
- bot_id = %command.bot_id,
- message_id = %command.origin.message_id,
- channel_id = %command.origin.channel_id,
- thread_id = %command.origin.thread_id,
- agent.trigger.kind = "mention",
- agent.session.id = tracing::field::Empty,
- ))]
- async fn open(&self, session_id: AgentSessionId, command: OpenSession) -> Result<()> {
- let OpenSession {
- bot_id,
- runtime,
- origin,
- } = command;
- tracing::Span::current().record("agent.session.id", tracing::field::display(session_id));
- let defaults = self.defaults.for_bot(bot_id);
- let repo_url = defaults.repo_url.clone();
- let sandbox_size = self.sessions.user_sandbox_size(&origin.sender).await?;
-
- // Provisioned before the session exists, because the row is what makes
- // the token mean anything: it carries the hash the proxy recognises.
- // Minted here, where the session's owner is in hand, and only here -
- // the token is scoped to this session and spends this person's
- // credentials, so there is nowhere else it could correctly come from.
- let egress = self
- .egress
- .provision(session_id, &origin.sender, &repo_url)
- .await?;
-
- self.sessions
- .create_session(CreateAgentSessionParams {
- id: session_id,
- owner_id: origin.sender.clone(),
- bot_id,
- thread_id: Some(origin.thread_id),
- originating_message_id: Some(origin.message_id),
- model: runtime.model.clone(),
- harness: runtime.harness.clone(),
- repo_url: Some(repo_url.clone()),
- // Managed sandboxes run in the path baked into their image.
- workspace: agent_session::MANAGED_CONTAINER_WORKSPACE.to_owned(),
- sandbox_size,
- // A mention carries no instructions: the prompt is whatever
- // was said in the channel, and nothing there states how the
- // runtime should work.
- instructions: None,
- egress_token_hash: Some(egress.session_token_hash),
- // This open came from the trigger pipeline seeing the mention.
- })
- .await?;
-
- let mcp_servers = egress.sandbox.acp_servers();
- let container = match self
- .containers
- .spawn(SpawnContainer {
- session_id,
- kind: runtime.kind,
- size: sandbox_size,
- egress: egress.sandbox,
- })
- .await
- {
- Ok(container) => container,
- Err(error) => {
- let _ = self
- .sessions
- .mark_disconnected(session_id)
- .await
- .inspect_err(|status_error| {
- tracing::error!(
- error = ?status_error,
- %session_id,
- "failed to mark an unprovisioned session disconnected"
- );
- });
- return Err(error);
- }
- };
- self.sessions
- .attach_session(
- session_id,
- RuntimeAttachment::solo(container).mcp_servers(mcp_servers),
- )
- .await?;
- // The first prompt goes through the same door as every later one:
- // queued raw, then dispatched - which is where it is composed with
- // channel context and announced as the chip the replies render into.
- // One door is what holds the one-turn-in-flight invariant from the
- // session's very first action.
- self.enqueue_then_dispatch(
- session_id,
- DeliverAction {
- id: AgentActionId::mint(),
- action: AgentAction::prompt(origin.content),
- actor: Some(origin.sender),
- announce: Some(AnnounceOrigin {
- channel_id: origin.channel_id,
- thread_id: origin.thread_id,
- message_id: origin.message_id,
- }),
- },
- )
- .await?;
- Ok(())
- }
-
- /// Deliver one already-composed action to the session's runtime.
- ///
- /// Announcing and composition are not this function's business: both
- /// belong to dispatch (see [`Self::dispatch_next`]), which is the only
- /// path a turn-occupying prompt travels. Non-turn-occupying actions
- /// (set-model, stop) arrive here directly and need neither.
- #[tracing::instrument(err, skip(self, command), fields(agent.session.id = %session_id))]
- async fn deliver(&self, session_id: AgentSessionId, command: DeliverAction) -> Result<()> {
- let DeliverAction {
- id,
- action,
- actor,
- announce: _,
- } = command;
-
- match self
- .sessions
- .send_action(session_id, actor.clone(), action.clone(), id)
- .await
- {
- Ok(()) => {}
- // Nothing is attached, so get this session onto a transport and
- // retry against it. Same id: the first attempt never reached the
- // wire.
- Err(AgentSessionError::Disconnected(_)) => {
- let session = self.sessions.get_session(session_id).await?;
- if AgentKind::for_session(session.bot_id, &session.harness).is_managed() {
- let container = self.containers.resume(session_id).await?;
- let mcp_servers = self
- .resumed_mcp_servers(session_id, &session.owner_id)
- .await?;
- self.sessions
- .attach_session(
- session_id,
- RuntimeAttachment::solo(container).mcp_servers(mcp_servers),
- )
- .await?;
- } else {
- // An external runtime is not ours to start - only its
- // operator can dial - but a bot whose runtime is already
- // connected just has not had this session bound to it
- // yet. That is the ordinary case: sessions bind when they
- // are prompted, not when the runtime dials, so the first
- // prompt after a reconnect is what restores the session.
- let Some(attachment) = self.runtimes.bind(session.bot_id, session_id).await
- else {
- // Kept in the session vocabulary so transports report
- // it as a disconnect, not an internal error.
- return Err(HarnessError::Session(AgentSessionError::Disconnected(
- session_id,
- )));
- };
- self.sessions.attach_session(session_id, attachment).await?;
- }
- self.sessions
- .send_action(session_id, actor, action, id)
- .await?;
- }
- Err(error) => return Err(error.into()),
- }
- Ok(())
- }
-
- /// Compose a prompt in place. Compact and other actions are left as-is.
- ///
- /// Channel context is loaded when the prompt named an origin; a lookup
- /// failure still composes, with empty history, so a transient context
- /// outage cannot eat the prompt.
- async fn compose_action(
- &self,
- action: &mut AgentAction,
- actor: Option<&MacroUserIdStr<'static>>,
- announce: Option<&AnnounceOrigin>,
- ) -> Result<()> {
- let AgentAction::Prompt(prompt) = action else {
- return Ok(());
- };
- let raw_prompt = prompt.prompt.clone();
- let prior_messages = if let Some(origin) = announce {
- Some(
- self.load_prompt_context(origin.channel_id, origin.message_id, actor)
- .await,
- )
- } else {
- None
- };
- prompt.prompt = self
- .prompt_composer
- .compose(&raw_prompt, prior_messages.as_deref())
- .await?;
- prompt.set_name_source(raw_prompt);
- Ok(())
- }
-
- async fn load_prompt_context(
- &self,
- channel_id: macro_uuid::Uuid,
- message_id: macro_uuid::Uuid,
- actor: Option<&MacroUserIdStr<'static>>,
- ) -> Vec<crate::domain::model::PriorChannelMessage> {
- async {
- if let Some(actor) = actor {
- self.prompt_context
- .authorize_member(actor, channel_id)
- .await?;
- }
- self.prompt_context
- .preceding_messages(channel_id, message_id)
- .await
- }
- .await
- .inspect_err(|error| {
- // Trigger events are admitted at-most-once. Context is useful,
- // but a transient lookup failure must not discard the prompt.
- tracing::warn!(
- error = ?error,
- %channel_id,
- %message_id,
- "sending agent prompt without channel history"
- );
- })
- .unwrap_or_default()
- }
-
- /// Who, if anyone, should be told that this landed.
- ///
- /// Only prompts are announced, and only when the caller named an origin
- /// to answer back into. A session has no channel of its own, so an origin
- /// is never redundant.
- async fn announcement(
- &self,
- session_id: AgentSessionId,
- action: &AgentAction,
- actor: Option<&MacroUserIdStr<'static>>,
- announce: Option<AnnounceOrigin>,
- ) -> Result<Option<SessionAnnouncement>> {
- let (Some(origin), Some(triggered_by), AgentAction::Prompt(prompt)) =
- (announce, actor, action)
- else {
- return Ok(None);
- };
-
- // The announcement posts as the session's own bot, which only the
- // row remembers.
- let session = self.sessions.get_session(session_id).await?;
-
- Ok(Some(SessionAnnouncement {
- session_id,
- bot_id: session.bot_id,
- origin_channel_id: origin.channel_id,
- origin_thread_id: origin.thread_id,
- origin_message_id: origin.message_id,
- prompted_message_id: self.sessions.next_prompt_message_id(session_id).await?,
- prompted_content: prompt.prompt.clone(),
- triggered_by: triggered_by.clone(),
- }))
- }
-}
-
-async fn run_session_worker<
- Sessions,
- Containers,
- Announcer,
- Runtimes,
- PromptContext,
- PromptComposer,
- Egress,
->(
- session_id: AgentSessionId,
- inner: Arc<
- AgentHarnessInner<
- Sessions,
- Containers,
- Announcer,
- Runtimes,
- PromptContext,
- PromptComposer,
- Egress,
- >,
- >,
- mut receiver: mpsc::UnboundedReceiver<QueuedCommand>,
-) where
- Sessions: AgentSessionService,
- Containers: ContainerManager,
- Announcer: SessionAnnouncer,
- Runtimes: RuntimeConnections,
- PromptContext: ChannelPromptContext,
- PromptComposer: AgentPromptComposer,
- Egress: SandboxEgressProvisioner,
-{
- while let Some(queued) = receiver.recv().await {
- let QueuedCommand {
- command,
- completed,
- span,
- route,
- } = queued;
- let result = if route {
- inner
- .route_then_execute(session_id, command)
- .instrument(span)
- .await
- } else {
- inner.execute(session_id, command).instrument(span).await
- };
- let _ = completed.send(result);
- }
-}
diff --git a/crates/agent_harness/src/domain/service/deliver.rs b/crates/agent_harness/src/domain/service/deliver.rs
new file mode 100644
index 0000000000..d60e82a0c9
--- /dev/null
+++ b/crates/agent_harness/src/domain/service/deliver.rs
@@ -0,0 +1,186 @@
+//! Delivering one queued action to the running agent: announce it in the
+//! channel, compose it with channel context, and prompt the runtime.
+
+use super::*;
+
+impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
+ AgentHarnessInner<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ >
+where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+ PromptContext: ChannelPromptContext,
+ PromptComposer: AgentPromptComposer,
+ Egress: SandboxEgressProvisioner,
+{
+ /// Deliver one already-composed action to the session's runtime.
+ ///
+ /// Announcing and composition are not this function's business: both
+ /// belong to dispatch (see [`Self::dispatch_next`]), which is the only
+ /// path a turn-occupying prompt travels. Non-turn-occupying actions
+ /// (set-model, stop) arrive here directly and need neither.
+ #[tracing::instrument(err, skip(self, command), fields(agent.session.id = %session_id))]
+ pub(super) async fn deliver(
+ &self,
+ session_id: AgentSessionId,
+ command: DeliverAction,
+ ) -> Result<()> {
+ let DeliverAction {
+ id,
+ action,
+ actor,
+ announce: _,
+ } = command;
+
+ match self
+ .sessions
+ .send_action(session_id, actor.clone(), action.clone(), id)
+ .await
+ {
+ Ok(()) => {}
+ // Nothing is attached, so get this session onto a transport and
+ // retry against it. Same id: the first attempt never reached the
+ // wire.
+ Err(AgentSessionError::Disconnected(_)) => {
+ let session = self.sessions.get_session(session_id).await?;
+ if AgentKind::for_session(session.bot_id, &session.harness).is_managed() {
+ let container = self.containers.resume(session_id).await?;
+ let mcp_servers = self
+ .resumed_mcp_servers(session_id, &session.owner_id, &session.mcp_servers)
+ .await?;
+ self.sessions
+ .attach_session(
+ session_id,
+ RuntimeAttachment::solo(container).mcp_servers(mcp_servers),
+ )
+ .await?;
+ } else {
+ // An external runtime is not ours to start - only its
+ // operator can dial - but a bot whose runtime is already
+ // connected just has not had this session bound to it
+ // yet. That is the ordinary case: sessions bind when they
+ // are prompted, not when the runtime dials, so the first
+ // prompt after a reconnect is what restores the session.
+ let Some(attachment) = self.runtimes.bind(session.bot_id, session_id).await
+ else {
+ // Kept in the session vocabulary so transports report
+ // it as a disconnect, not an internal error.
+ return Err(HarnessError::Session(AgentSessionError::Disconnected(
+ session_id,
+ )));
+ };
+ self.sessions.attach_session(session_id, attachment).await?;
+ }
+ self.sessions
+ .send_action(session_id, actor, action, id)
+ .await?;
+ }
+ Err(error) => return Err(error.into()),
+ }
+ Ok(())
+ }
+
+ /// Compose a prompt in place. Compact and other actions are left as-is.
+ ///
+ /// Channel context is loaded when the prompt named an origin; a lookup
+ /// failure still composes, with empty history, so a transient context
+ /// outage cannot eat the prompt.
+ pub(super) async fn compose_action(
+ &self,
+ action: &mut AgentAction,
+ actor: Option<&MacroUserIdStr<'static>>,
+ announce: Option<&AnnounceOrigin>,
+ ) -> Result<()> {
+ let AgentAction::Prompt(prompt) = action else {
+ return Ok(());
+ };
+ let raw_prompt = prompt.prompt.clone();
+ let prior_messages = if let Some(origin) = announce {
+ Some(
+ self.load_prompt_context(origin.channel_id, origin.message_id, actor)
+ .await,
+ )
+ } else {
+ None
+ };
+ prompt.prompt = self
+ .prompt_composer
+ .compose(&raw_prompt, prior_messages.as_deref())
+ .await?;
+ prompt.set_name_source(raw_prompt);
+ Ok(())
+ }
+
+ pub(super) async fn load_prompt_context(
+ &self,
+ channel_id: macro_uuid::Uuid,
+ message_id: macro_uuid::Uuid,
+ actor: Option<&MacroUserIdStr<'static>>,
+ ) -> Vec<crate::domain::model::PriorChannelMessage> {
+ async {
+ if let Some(actor) = actor {
+ self.prompt_context
+ .authorize_member(actor, channel_id)
+ .await?;
+ }
+ self.prompt_context
+ .preceding_messages(channel_id, message_id)
+ .await
+ }
+ .await
+ .inspect_err(|error| {
+ // Trigger events are admitted at-most-once. Context is useful,
+ // but a transient lookup failure must not discard the prompt.
+ tracing::warn!(
+ error = ?error,
+ %channel_id,
+ %message_id,
+ "sending agent prompt without channel history"
+ );
+ })
+ .unwrap_or_default()
+ }
+
+ /// Who, if anyone, should be told that this landed.
+ ///
+ /// Only prompts are announced, and only when the caller named an origin
+ /// to answer back into. A session has no channel of its own, so an origin
+ /// is never redundant.
+ pub(super) async fn announcement(
+ &self,
+ session_id: AgentSessionId,
+ action: &AgentAction,
+ actor: Option<&MacroUserIdStr<'static>>,
+ announce: Option<AnnounceOrigin>,
+ ) -> Result<Option<SessionAnnouncement>> {
+ let (Some(origin), Some(triggered_by), AgentAction::Prompt(prompt)) =
+ (announce, actor, action)
+ else {
+ return Ok(None);
+ };
+
+ // The announcement posts as the session's own bot, which only the
+ // row remembers.
+ let session = self.sessions.get_session(session_id).await?;
+
+ Ok(Some(SessionAnnouncement {
+ session_id,
+ bot_id: session.bot_id,
+ origin_channel_id: origin.channel_id,
+ origin_thread_id: origin.thread_id,
+ origin_message_id: origin.message_id,
+ prompted_message_id: self.sessions.next_prompt_message_id(session_id).await?,
+ prompted_content: prompt.prompt.clone(),
+ triggered_by: triggered_by.clone(),
+ }))
+ }
+}
diff --git a/crates/agent_harness/src/domain/service/lifecycle.rs b/crates/agent_harness/src/domain/service/lifecycle.rs
new file mode 100644
index 0000000000..0fb0818667
--- /dev/null
+++ b/crates/agent_harness/src/domain/service/lifecycle.rs
@@ -0,0 +1,265 @@
+//! A session after it is open: control events from the app, sandbox sizing,
+//! turn boundaries, and teardown.
+
+use super::*;
+
+/// The harness is what holds a session's live resources, so it is what the
+/// control routes notify. Both operations go through the per-session queue, so
+/// a teardown cannot land in the middle of an open and a model change cannot
+/// overtake the prompt it was meant to follow.
+impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
+ AgentSessionNotificationRecipient
+ for AgentHarnessService<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ >
+where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+ PromptContext: ChannelPromptContext,
+ PromptComposer: AgentPromptComposer,
+ Egress: SandboxEgressProvisioner,
+{
+ async fn session_deleted(
+ &self,
+ id: AgentSessionId,
+ ) -> agent_session::domain::error::Result<()> {
+ self.execute(id, HarnessCommand::Delete)
+ .await
+ .map(drop)
+ .map_err(into_session_error)
+ }
+
+ async fn control_event(
+ &self,
+ id: AgentSessionId,
+ event: ControlEvent,
+ ) -> agent_session::domain::error::Result<AcceptedControl> {
+ let action_id = AgentActionId::mint();
+ let outcome = self
+ .execute(
+ id,
+ HarnessCommand::Deliver(DeliverAction::control(action_id, event)),
+ )
+ .await
+ .map_err(into_session_error)?;
+ Ok(AcceptedControl {
+ action_id,
+ disposition: match outcome {
+ CommandOutcome::Completed => ControlDisposition::Sent,
+ CommandOutcome::Queued => ControlDisposition::Queued,
+ },
+ })
+ }
+
+ /// A local read on purpose: the queue lives beside the session's live
+ /// actor, and this replica answers for what it holds. A reader landing on
+ /// a non-managing replica sees an empty queue rather than an error.
+ async fn queued_controls(
+ &self,
+ id: AgentSessionId,
+ ) -> agent_session::domain::error::Result<Vec<QueuedControl>> {
+ Ok(self.inner.queues.list(id))
+ }
+
+ async fn edit_queued_control(
+ &self,
+ id: AgentSessionId,
+ action_id: AgentActionId,
+ prompt: String,
+ actor: Option<MacroUserIdStr<'static>>,
+ ) -> agent_session::domain::error::Result<()> {
+ self.execute(
+ id,
+ HarnessCommand::EditQueued {
+ action_id,
+ prompt,
+ actor,
+ },
+ )
+ .await
+ .map(drop)
+ .map_err(into_session_error)
+ }
+
+ async fn remove_queued_control(
+ &self,
+ id: AgentSessionId,
+ action_id: AgentActionId,
+ actor: Option<MacroUserIdStr<'static>>,
+ ) -> agent_session::domain::error::Result<()> {
+ self.execute(id, HarnessCommand::RemoveQueued { action_id, actor })
+ .await
+ .map(drop)
+ .map_err(into_session_error)
+ }
+
+ async fn set_sandbox_size(
+ &self,
+ id: AgentSessionId,
+ size: SandboxSize,
+ ) -> agent_session::domain::error::Result<()> {
+ self.execute(id, HarnessCommand::SetSandboxSize(size))
+ .await
+ .map(drop)
+ .map_err(into_session_error)
+ }
+
+ async fn session_harness(
+ &self,
+ id: AgentSessionId,
+ ) -> agent_session::domain::error::Result<Option<harness_id::HarnessId>> {
+ // The row is the source of truth for which bot the session runs, and
+ // the binding resolves the bot's current harness the same way `bind`
+ // does at delivery time.
+ let session = self.inner.sessions.get_session(id).await?;
+ self.inner
+ .runtimes
+ .bound_harness(session.bot_id)
+ .await
+ .map_err(AgentSessionError::Unknown)
+ }
+}
+
+/// The queue drains on the session's own command worker, so both signals
+/// only admit an internal command there and return. Admission is synchronous
+/// inside [`AgentHarnessService::execute_here`]; the returned future only
+/// awaits the completion, which nothing here needs.
+impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
+ agent_session::domain::ports::SessionTurnObserver
+ for AgentHarnessService<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ >
+where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+ PromptContext: ChannelPromptContext,
+ PromptComposer: AgentPromptComposer,
+ Egress: SandboxEgressProvisioner,
+{
+ fn turn_ended(&self, id: AgentSessionId) {
+ drop(self.execute_here(id, HarnessCommand::TurnEnded));
+ }
+
+ fn session_stopped(&self, id: AgentSessionId) {
+ drop(self.execute_here(id, HarnessCommand::SessionStopped));
+ }
+}
+
+impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
+ AgentHarnessInner<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ >
+where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+ PromptContext: ChannelPromptContext,
+ PromptComposer: AgentPromptComposer,
+ Egress: SandboxEgressProvisioner,
+{
+ /// The MCP servers to advertise when reattaching to an existing container.
+ ///
+ /// The raw session token exists in exactly one place after spawn - the
+ /// container's own environment - so it is read back from there and wrapped
+ /// in a fresh listing of the owner's connected servers. A container that
+ /// holds no token (a provider whose sessions carry no egress environment,
+ /// or a sandbox from before tokens existed) gets no servers, which is
+ /// also everything it could do with them.
+ #[tracing::instrument(err, skip(self, owner), fields(%session_id, %owner))]
+ pub(super) async fn resumed_mcp_servers(
+ &self,
+ session_id: AgentSessionId,
+ owner: &MacroUserIdStr<'static>,
+ selection: &AgentMcpServers,
+ ) -> Result<Vec<agent_client_protocol::schema::v1::McpServer>> {
+ let Some(session_token) = self.containers.session_token(session_id).await? else {
+ tracing::debug!("container holds no egress token; restoring no MCP servers");
+ return Ok(Vec::new());
+ };
+ Ok(self
+ .egress
+ .restore(owner, session_token, selection)
+ .await?
+ .acp_servers())
+ }
+
+ /// Release everything the session holds, then delete it.
+ ///
+ /// The durable delete goes last on purpose. Crashing between the two
+ /// leaves a session whose container is gone, which `resume` heals by
+ /// spawning a new one; the other order leaves a paid sandbox that nothing
+ /// knows to reap.
+ #[tracing::instrument(err, skip(self), fields(%session_id))]
+ pub(super) async fn delete(&self, session_id: AgentSessionId) -> Result<()> {
+ self.sessions.close_session(session_id).await?;
+ self.containers.teardown(session_id).await?;
+ self.sessions.delete_session(session_id).await?;
+ Ok(())
+ }
+
+ /// Apply `size` to this session's sandbox and remember it as the owner's default.
+ ///
+ /// The container manager reports whether the change is in-place, needs a
+ /// stop, or is unsupported. Disk is never changed.
+ #[tracing::instrument(err, skip(self), fields(%session_id, %size))]
+ pub(super) async fn apply_sandbox_size(
+ &self,
+ session_id: AgentSessionId,
+ size: SandboxSize,
+ ) -> Result<()> {
+ let session = self.sessions.get_session(session_id).await?;
+ let effect = self.containers.resize_effect(session.sandbox_size, size);
+ // Only a sandboxed coder has a sandbox to act on: a Cursor session
+ // runs in Cursor's cloud, the in-memory bot has no sandbox, and an
+ // external bot provisions its own. For all three, the size is only
+ // recorded below as a preference.
+ if AgentKind::for_session(session.bot_id, &session.harness) == AgentKind::SandboxedCoder
+ && effect != SandboxResizeEffect::NoOp
+ {
+ if effect == SandboxResizeEffect::Restart {
+ self.sessions.close_session(session_id).await?;
+ }
+ self.containers.resize(session_id, size).await?;
+ if effect == SandboxResizeEffect::Restart {
+ let container = self.containers.resume(session_id).await?;
+ let mcp_servers = self
+ .resumed_mcp_servers(session_id, &session.owner_id, &session.mcp_servers)
+ .await?;
+ self.sessions
+ .attach_session(
+ session_id,
+ RuntimeAttachment::solo(container).mcp_servers(mcp_servers),
+ )
+ .await?;
+ }
+ }
+ self.sessions.set_sandbox_size(session_id, size).await?;
+ self.sessions
+ .set_user_sandbox_size(&session.owner_id, size)
+ .await?;
+ Ok(())
+ }
+}
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
new file mode 100644
index 0000000000..36faffa7cf
--- /dev/null
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -0,0 +1,352 @@
+//! Opening sessions: from a channel mention, from the create menu, and for an
+//! external runtime that dials in. Each creates the row, provisions egress
+//! where there is a sandbox to give it to, and attaches the runtime.
+
+use super::*;
+
+/// External sessions create the row and announce - the magic-chip message
+/// the session's bot posts into the mention's thread, which is where the
+/// app renders the session's replies. No sandbox (the runtime dials in) and
+/// no first prompt (the runtime sends it through the control endpoint).
+/// The announcement is best-effort: a session a runtime is about to serve
+/// must not die because the courtesy post failed, most plainly when the bot
+/// cannot post in the claimed channel.
+impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
+ agent_session::domain::ports::SessionOpener
+ for AgentHarnessService<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ >
+where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+ PromptContext: ChannelPromptContext,
+ PromptComposer: AgentPromptComposer,
+ Egress: SandboxEgressProvisioner,
+{
+ async fn open_external_session(
+ &self,
+ request: agent_session::domain::ports::OpenExternalAgentSession,
+ ) -> agent_session::domain::error::Result<AgentSession> {
+ let defaults = self.inner.defaults.for_bot(request.bot_id);
+ let session = self
+ .inner
+ .sessions
+ .create_session(CreateAgentSessionParams {
+ id: AgentSessionId::new(),
+ owner_id: request.owner.clone(),
+ bot_id: request.bot_id,
+ thread_id: request.thread.as_ref().map(|thread| thread.thread_id),
+ originating_message_id: request.thread.as_ref().map(|thread| thread.message_id),
+ model: defaults.model.clone(),
+ harness: defaults.harness.clone(),
+ repo_url: request.repo_url,
+ workspace: request.workspace,
+ sandbox_size: SandboxSize::Default,
+ instructions: request.instructions,
+ // No egress, so no MCP servers of ours to select from.
+ mcp_servers: AgentMcpServers::OwnerConnections,
+ // No sandbox: the runtime dials in and reaches the network on
+ // its operator's own terms, so there is no egress token.
+ egress_token_hash: None,
+ // The thread linkage is the caller's claim, not an observed
+ // mention; it must not grant the channel anything.
+ })
+ .await?;
+
+ if let Some(thread) = request.thread {
+ let announcement = SessionAnnouncement {
+ session_id: session.id,
+ bot_id: request.bot_id,
+ origin_channel_id: thread.channel_id,
+ origin_thread_id: thread.thread_id,
+ origin_message_id: thread.message_id,
+ prompted_message_id: MessageId::first(AuthorKind::User),
+ prompted_content: thread.content,
+ triggered_by: request.owner,
+ };
+ if let Err(error) = self.inner.announcer.announce(announcement).await {
+ tracing::warn!(
+ error = ?error,
+ session = %session.id,
+ "external session announcement failed; the session runs unannounced"
+ );
+ }
+ }
+
+ Ok(session)
+ }
+
+ /// Provision the managed-default bot's runtime, open a session on it,
+ /// and deliver the first prompt if one came with the request.
+ ///
+ /// Nothing is announced: a managed session opened this way has no
+ /// originating mention and no thread to answer back into. The runtime is
+ /// spawned before the session is attached because there is nothing to
+ /// attach to until it exists.
+ async fn open_managed_session(
+ &self,
+ request: agent_session::domain::ports::OpenManagedSession,
+ ) -> agent_session::domain::error::Result<AgentSession> {
+ let defaults = self.inner.defaults.managed();
+ let sandbox_size = self
+ .inner
+ .sessions
+ .user_sandbox_size(&request.owner)
+ .await?;
+ let session_id = AgentSessionId::new();
+ // Same ordering as the trigger path's open: the token has to be minted
+ // before the row, because the row is what carries the hash that makes
+ // it mean anything.
+ let egress = self
+ .inner
+ .egress
+ .provision(
+ session_id,
+ &request.owner,
+ &defaults.repo_url,
+ &AgentMcpServers::OwnerConnections,
+ )
+ .await
+ .map_err(into_session_error)?;
+ let session = self
+ .inner
+ .sessions
+ .create_session(CreateAgentSessionParams {
+ id: session_id,
+ owner_id: request.owner.clone(),
+ bot_id: defaults.bot_id,
+ thread_id: None,
+ originating_message_id: None,
+ model: defaults.model.clone(),
+ harness: defaults.harness.clone(),
+ repo_url: Some(defaults.repo_url.clone()),
+ // Managed sandboxes run in the path baked into their image.
+ workspace: agent_session::MANAGED_CONTAINER_WORKSPACE.to_owned(),
+ sandbox_size,
+ instructions: request.instructions,
+ // A fixed system agent has no configuration to select from.
+ mcp_servers: AgentMcpServers::OwnerConnections,
+ egress_token_hash: Some(egress.session_token_hash),
+ })
+ .await?;
+
+ let mcp_servers = egress.sandbox.acp_servers();
+ let container = match self
+ .inner
+ .containers
+ .spawn(SpawnContainer {
+ session_id: session.id,
+ kind: AgentKind::for_session(session.bot_id, &session.harness),
+ size: sandbox_size,
+ egress: egress.sandbox,
+ })
+ .await
+ {
+ Ok(container) => container,
+ // The row is already persisted, so a sandbox that never arrived
+ // would otherwise leave a session claiming to be live. Same
+ // handling as the trigger path's open.
+ Err(error) => {
+ let _ = self
+ .inner
+ .sessions
+ .mark_disconnected(session.id)
+ .await
+ .inspect_err(|status_error| {
+ tracing::error!(
+ error = ?status_error,
+ session_id = %session.id,
+ "failed to mark an unprovisioned session disconnected"
+ );
+ });
+ return Err(into_session_error(error));
+ }
+ };
+ self.inner
+ .sessions
+ .attach_session(
+ session.id,
+ RuntimeAttachment::solo(container).mcp_servers(mcp_servers),
+ )
+ .await?;
+
+ // Raw, through the session's own command worker: dispatch is where a
+ // prompt is composed, and the worker is what serializes this first
+ // prompt against any control prompt racing the session's birth.
+ if let Some(raw_prompt) = request.prompt {
+ self.execute_here(
+ session.id,
+ HarnessCommand::Deliver(DeliverAction {
+ id: AgentActionId::mint(),
+ action: AgentAction::prompt(raw_prompt),
+ actor: Some(request.owner),
+ announce: None,
+ }),
+ )
+ .await
+ .map_err(into_session_error)?;
+ }
+
+ Ok(session)
+ }
+
+ async fn find_thread_session(
+ &self,
+ thread_id: macro_uuid::Uuid,
+ bot_id: BotId,
+ ) -> agent_session::domain::error::Result<Option<AgentSessionId>> {
+ match self
+ .inner
+ .sessions
+ .find_for_channel(Some(thread_id), Some(bot_id))
+ .await?
+ {
+ agent_session::domain::model::ChannelSession::CreatedFromThread(session) => {
+ Ok(Some(session.id))
+ }
+ agent_session::domain::model::ChannelSession::None => Ok(None),
+ }
+ }
+}
+
+impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
+ AgentHarnessInner<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ >
+where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+ PromptContext: ChannelPromptContext,
+ PromptComposer: AgentPromptComposer,
+ Egress: SandboxEgressProvisioner,
+{
+ #[tracing::instrument(err, skip(self, command), fields(
+ %session_id,
+ bot_id = %command.bot_id,
+ message_id = %command.origin.message_id,
+ channel_id = %command.origin.channel_id,
+ thread_id = %command.origin.thread_id,
+ agent.trigger.kind = "mention",
+ agent.session.id = tracing::field::Empty,
+ ))]
+ pub(super) async fn open(
+ &self,
+ session_id: AgentSessionId,
+ command: OpenSession,
+ ) -> Result<()> {
+ let OpenSession {
+ bot_id,
+ runtime,
+ origin,
+ } = command;
+ tracing::Span::current().record("agent.session.id", tracing::field::display(session_id));
+ let defaults = self.defaults.for_bot(bot_id);
+ let repo_url = defaults.repo_url.clone();
+ let sandbox_size = self.sessions.user_sandbox_size(&origin.sender).await?;
+
+ // Provisioned before the session exists, because the row is what makes
+ // the token mean anything: it carries the hash the proxy recognises.
+ // Minted here, where the session's owner is in hand, and only here -
+ // the token is scoped to this session and spends this person's
+ // credentials, so there is nowhere else it could correctly come from.
+ let egress = self
+ .egress
+ .provision(session_id, &origin.sender, &repo_url, &runtime.mcp_servers)
+ .await?;
+
+ self.sessions
+ .create_session(CreateAgentSessionParams {
+ id: session_id,
+ owner_id: origin.sender.clone(),
+ bot_id,
+ thread_id: Some(origin.thread_id),
+ originating_message_id: Some(origin.message_id),
+ model: runtime.model.clone(),
+ harness: runtime.harness.clone(),
+ repo_url: Some(repo_url.clone()),
+ // Managed sandboxes run in the path baked into their image.
+ workspace: agent_session::MANAGED_CONTAINER_WORKSPACE.to_owned(),
+ sandbox_size,
+ // A mention carries no instructions: the prompt is whatever
+ // was said in the channel, and nothing there states how the
+ // runtime should work.
+ instructions: None,
+ // Snapshotted so the proxy enforces exactly what this attach
+ // advertised, for as long as the session lives.
+ mcp_servers: runtime.mcp_servers.clone(),
+ egress_token_hash: Some(egress.session_token_hash),
+ // This open came from the trigger pipeline seeing the mention.
+ })
+ .await?;
+
+ let mcp_servers = egress.sandbox.acp_servers();
+ let container = match self
+ .containers
+ .spawn(SpawnContainer {
+ session_id,
+ kind: runtime.kind,
+ size: sandbox_size,
+ egress: egress.sandbox,
+ })
+ .await
+ {
+ Ok(container) => container,
+ Err(error) => {
+ let _ = self
+ .sessions
+ .mark_disconnected(session_id)
+ .await
+ .inspect_err(|status_error| {
+ tracing::error!(
+ error = ?status_error,
+ %session_id,
+ "failed to mark an unprovisioned session disconnected"
+ );
+ });
+ return Err(error);
+ }
+ };
+ self.sessions
+ .attach_session(
+ session_id,
+ RuntimeAttachment::solo(container).mcp_servers(mcp_servers),
+ )
+ .await?;
+ // The first prompt goes through the same door as every later one:
+ // queued raw, then dispatched - which is where it is composed with
+ // channel context and announced as the chip the replies render into.
+ // One door is what holds the one-turn-in-flight invariant from the
+ // session's very first action.
+ self.enqueue_then_dispatch(
+ session_id,
+ DeliverAction {
+ id: AgentActionId::mint(),
+ action: AgentAction::prompt(origin.content),
+ actor: Some(origin.sender),
+ announce: Some(AnnounceOrigin {
+ channel_id: origin.channel_id,
+ thread_id: origin.thread_id,
+ message_id: origin.message_id,
+ }),
+ },
+ )
+ .await?;
+ Ok(())
+ }
+}
diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rs
new file mode 100644
index 0000000000..8dfcac4600
--- /dev/null
+++ b/crates/agent_harness/src/domain/service/queue.rs
@@ -0,0 +1,530 @@
+//! The per-session command queue: admission, the worker that drains it one
+//! command at a time, and routing to the replica that holds the session.
+
+use super::*;
+
+pub(super) type SessionWorkers = DashMap<AgentSessionId, mpsc::UnboundedSender<QueuedCommand>>;
+
+pub(super) struct QueuedCommand {
+ command: HarnessCommand,
+ completed: oneshot::Sender<Result<CommandOutcome>>,
+ /// The caller's span, carried across the queue so the work the worker does
+ /// on its own task still hangs off whatever triggered it.
+ span: tracing::Span,
+ /// Whether the worker resolves the session's managing replica before
+ /// executing. Commands admitted at an ingress route; a command received
+ /// *as* a forward executes here unconditionally, which is what makes
+ /// forwarding single-hop - two replicas with momentarily different lease
+ /// views cannot bounce a command between each other.
+ route: bool,
+}
+
+/// [`CommandForwarder`], object-safe.
+///
+/// Held erased inside the service so forwarding does not become an eighth
+/// type parameter on every impl block; the public port keeps its natural
+/// `impl Future` shape and this shim boxes at the one internal call site.
+pub(super) trait ErasedForwarder: Send + Sync + 'static {
+ fn forward<'a>(
+ &'a self,
+ session: AgentSessionId,
+ command: HarnessCommand,
+ target: crate::domain::ports::CommandTarget,
+ ) -> std::pin::Pin<Box<dyn Future<Output = Result<CommandOutcome>> + Send + 'a>>;
+}
+
+impl<F: CommandForwarder> ErasedForwarder for F {
+ fn forward<'a>(
+ &'a self,
+ session: AgentSessionId,
+ command: HarnessCommand,
+ target: crate::domain::ports::CommandTarget,
+ ) -> std::pin::Pin<Box<dyn Future<Output = Result<CommandOutcome>> + Send + 'a>> {
+ Box::pin(CommandForwarder::forward(self, session, command, target))
+ }
+}
+
+impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
+ AgentHarnessService<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ >
+where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+ PromptContext: ChannelPromptContext,
+ PromptComposer: AgentPromptComposer,
+ Egress: SandboxEgressProvisioner,
+{
+ pub(super) fn enqueue(
+ &self,
+ session_id: AgentSessionId,
+ mut command: HarnessCommand,
+ route: bool,
+ ) -> impl Future<Output = Result<CommandOutcome>> + Send + 'static {
+ let caller = tracing::Span::current();
+ let result = loop {
+ let commands = self.commands(session_id);
+ let (completed, result) = oneshot::channel();
+ let queued = QueuedCommand {
+ command,
+ completed,
+ span: caller.clone(),
+ route,
+ };
+
+ match commands.send(queued) {
+ Ok(()) => break result,
+ Err(error) => {
+ command = error.0.command;
+ self.workers
+ .remove_if(&session_id, |_, current| current.same_channel(&commands));
+ }
+ }
+ };
+
+ async move {
+ result
+ .await
+ .map_err(|_| HarnessError::CommandWorkerStopped(session_id))?
+ }
+ }
+
+ pub(super) fn commands(
+ &self,
+ session_id: AgentSessionId,
+ ) -> mpsc::UnboundedSender<QueuedCommand> {
+ match self.workers.entry(session_id) {
+ Entry::Occupied(entry) => entry.get().clone(),
+ Entry::Vacant(entry) => {
+ let (commands, receiver) = mpsc::unbounded_channel();
+ entry.insert(commands.clone());
+ self.spawn_worker(session_id, receiver);
+ commands
+ }
+ }
+ }
+
+ pub(super) fn spawn_worker(
+ &self,
+ session_id: AgentSessionId,
+ receiver: mpsc::UnboundedReceiver<QueuedCommand>,
+ ) {
+ // The worker outlives the call that created it, so it has to carry the
+ // subscriber forward itself or every command it runs traces nowhere.
+ let inner = self.inner.clone();
+ tokio::spawn(run_session_worker(session_id, inner, receiver).with_current_subscriber());
+ }
+}
+
+impl<Sessions, Containers, Announcer, Runtimes, PromptContext, PromptComposer, Egress>
+ AgentHarnessInner<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ >
+where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+ PromptContext: ChannelPromptContext,
+ PromptComposer: AgentPromptComposer,
+ Egress: SandboxEgressProvisioner,
+{
+ /// Execute where the session's live actor is: locally when nobody (or
+ /// this replica) manages it, on the managing peer otherwise.
+ /// The routing decision is recorded on the span, not only logged: which of
+ /// the three answers the lease gave, which peer it named, and whether the
+ /// command left this process. Those are the fields you group by when a
+ /// replica is mishandling commands, and a log line cannot be aggregated.
+ #[tracing::instrument(
+ err,
+ skip(self, command),
+ fields(
+ %session_id,
+ agent.session.management = tracing::field::Empty,
+ agent.session.manager_replica = tracing::field::Empty,
+ agent.command.forwarded = tracing::field::Empty,
+ )
+ )]
+ pub(super) async fn route_then_execute(
+ &self,
+ session_id: AgentSessionId,
+ command: HarnessCommand,
+ ) -> Result<CommandOutcome> {
+ let span = tracing::Span::current();
+ // Open never routes: it is what creates the session row this routing
+ // would read, and a fresh id has no manager to defer to.
+ if matches!(command, HarnessCommand::Open(_)) {
+ span.record("agent.session.management", "open");
+ span.record("agent.command.forwarded", false);
+ return self.execute(session_id, command).await;
+ }
+ let manager = match self.sessions.management(session_id).await? {
+ SessionManagement::Unmanaged => {
+ span.record("agent.session.management", "unmanaged");
+ span.record("agent.command.forwarded", false);
+ let session = self.sessions.get_session(session_id).await?;
+ if AgentKind::for_session(session.bot_id, &session.harness) != AgentKind::External {
+ return self.execute(session_id, command).await;
+ }
+ let Some(harness) = self
+ .runtimes
+ .bound_harness(session.bot_id)
+ .await
+ .map_err(AgentSessionError::Unknown)?
+ else {
+ return self.execute(session_id, command).await;
+ };
+ if self.runtimes.is_connected(harness) {
+ return self.execute(session_id, command).await;
+ }
+ span.record("agent.command.forwarded", true);
+ return self
+ .forwarder
+ .forward(
+ session_id,
+ command,
+ crate::domain::ports::CommandTarget::Harness(harness),
+ )
+ .await;
+ }
+ SessionManagement::Ours => {
+ span.record("agent.session.management", "ours");
+ span.record("agent.command.forwarded", false);
+ return self.execute(session_id, command).await;
+ }
+ SessionManagement::Peer(manager) => manager,
+ };
+ span.record("agent.session.management", "peer");
+ span.record(
+ "agent.session.manager_replica",
+ tracing::field::display(manager.replica),
+ );
+ span.record("agent.command.forwarded", true);
+ tracing::info!(%session_id, peer = %manager.replica, "forwarding an agent session command");
+ self.forwarder
+ .forward(
+ session_id,
+ command,
+ crate::domain::ports::CommandTarget::Replica(manager.replica),
+ )
+ .await
+ }
+
+ pub(super) async fn execute(
+ &self,
+ session_id: AgentSessionId,
+ command: HarnessCommand,
+ ) -> Result<CommandOutcome> {
+ match &command {
+ HarnessCommand::Open(open)
+ if AgentKind::of(open.bot_id) == AgentKind::SandboxedCoder
+ && !is_macro_staff(&open.origin.sender) =>
+ {
+ return Err(AgentSessionError::Forbidden.into());
+ }
+ // The queue mutations sit behind the same staff gate as delivery:
+ // an edited entry is delivered later under its original identity,
+ // so rewriting (or dropping) what a Daytona session is about to
+ // run is the same privilege as prompting it.
+ HarnessCommand::Deliver(DeliverAction { actor, .. })
+ | HarnessCommand::EditQueued { actor, .. }
+ | HarnessCommand::RemoveQueued { actor, .. } => {
+ let session = self.sessions.get_session(session_id).await?;
+ if AgentKind::of(session.bot_id) == AgentKind::SandboxedCoder
+ && !actor.as_ref().is_some_and(is_macro_staff)
+ {
+ return Err(AgentSessionError::Forbidden.into());
+ }
+ }
+ HarnessCommand::Open(_)
+ | HarnessCommand::TurnEnded
+ | HarnessCommand::SessionStopped
+ | HarnessCommand::SetSandboxSize(_)
+ | HarnessCommand::Delete => {}
+ }
+
+ match command {
+ HarnessCommand::Open(command) => {
+ self.open(session_id, command).await?;
+ Ok(CommandOutcome::Completed)
+ }
+ // Turn-occupying actions go through the queue - the running
+ // turn's end is what dispatches them. Everything else delivers
+ // now: a stop rides alongside the turn it cancels, and that
+ // turn's cancelled answer is an ordinary turn end.
+ HarnessCommand::Deliver(command) if command.action.occupies_turn() => {
+ self.enqueue_then_dispatch(session_id, command).await
+ }
+ HarnessCommand::Deliver(command) => {
+ self.deliver(session_id, command).await?;
+ Ok(CommandOutcome::Completed)
+ }
+ HarnessCommand::EditQueued {
+ action_id,
+ prompt,
+ actor,
+ } => {
+ queue_result(
+ self.queues
+ .edit_prompt(session_id, action_id, prompt, actor),
+ session_id,
+ )?;
+ self.publish_queue(session_id).await;
+ Ok(CommandOutcome::Completed)
+ }
+ HarnessCommand::RemoveQueued { action_id, .. } => {
+ queue_result(self.queues.remove(session_id, action_id), session_id)?;
+ self.publish_queue(session_id).await;
+ Ok(CommandOutcome::Completed)
+ }
+ HarnessCommand::TurnEnded => {
+ self.busy.remove(&session_id);
+ let dispatched = self.dispatch_next(session_id).await;
+ // Published whatever dispatching did: a claim, a requeued
+ // failure, and an emptied queue are all changes a viewer is
+ // watching for.
+ self.publish_queue(session_id).await;
+ dispatched?;
+ Ok(CommandOutcome::Completed)
+ }
+ HarnessCommand::SessionStopped => {
+ self.busy.remove(&session_id);
+ Ok(CommandOutcome::Completed)
+ }
+ HarnessCommand::SetSandboxSize(size) => {
+ self.apply_sandbox_size(session_id, size).await?;
+ Ok(CommandOutcome::Completed)
+ }
+ HarnessCommand::Delete => {
+ self.delete(session_id).await?;
+ // The queue and busy mark die with the session: a deleted
+ // session's entries will never dispatch, and leaving them
+ // would leak them for the life of the process. The published
+ // empty snapshot is the viewers' goodbye.
+ self.busy.remove(&session_id);
+ self.queues.drop_session(session_id);
+ self.publish_queue(session_id).await;
+ Ok(CommandOutcome::Completed)
+ }
+ }
+ }
+
+ /// Queue a turn-occupying action, and dispatch the head of the queue
+ /// right away when no turn is running.
+ ///
+ /// The dispatched entry is usually the one just queued, but not
+ /// necessarily: entries can linger from a drain that failed, and FIFO
+ /// order holds regardless. The outcome reports what happened to *this*
+ /// action - still waiting, or on the wire.
+ pub(super) async fn enqueue_then_dispatch(
+ &self,
+ session_id: AgentSessionId,
+ command: DeliverAction,
+ ) -> Result<CommandOutcome> {
+ let action_id = command.id;
+ queue_result(
+ self.queues.enqueue(
+ session_id,
+ QueuedEntry {
+ action_id,
+ action: command.action,
+ actor: command.actor,
+ announce: command.announce,
+ announced: false,
+ created_at: chrono::Utc::now(),
+ },
+ ),
+ session_id,
+ )?;
+
+ let dispatched = if self.busy.contains_key(&session_id) {
+ Ok(())
+ } else {
+ self.dispatch_next(session_id).await
+ };
+ self.publish_queue(session_id).await;
+ dispatched?;
+
+ Ok(if self.queues.contains(session_id, action_id) {
+ CommandOutcome::Queued
+ } else {
+ CommandOutcome::Completed
+ })
+ }
+
+ /// Push the queue as it now stands to the session's viewers.
+ ///
+ /// Best-effort, like every realtime publish: a dropped snapshot costs a
+ /// viewer liveness until the next change, and the queue itself is intact -
+ /// so this logs and never fails the command it rides on.
+ pub(super) async fn publish_queue(&self, session_id: AgentSessionId) {
+ let _ = self
+ .sessions
+ .publish_queue_changed(AgentSessionQueueChanged {
+ agent_session_id: session_id,
+ entries: self.queues.list(session_id),
+ })
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(
+ error = ?error,
+ %session_id,
+ "failed to publish an agent session queue change"
+ );
+ });
+ }
+
+ /// Deliver the oldest queued action, marking the session busy on success.
+ ///
+ /// Composition runs first so a lexical failure never posts a chip for a
+ /// prompt that will not reach the agent. The chip is then announced
+ /// (from the raw text) before delivery, so it exists to anchor the turn
+ /// the agent streams into - and it is announced *at most once* per
+ /// entry: the claimed entry remembers a successful announce, so a
+ /// dispatch that fails after the chip posted retries without posting a
+ /// second one.
+ ///
+ /// A failed dispatch puts the entry back at the front: it stays next in
+ /// line for the next turn end or the next prompt, and stays visible in
+ /// the queue meanwhile. The error still propagates, so a caller whose
+ /// own action triggered this dispatch hears about it.
+ #[tracing::instrument(err, skip(self), fields(%session_id))]
+ pub(super) async fn dispatch_next(&self, session_id: AgentSessionId) -> Result<()> {
+ let Some(mut entry) = self.queues.claim_next(session_id) else {
+ return Ok(());
+ };
+
+ // Compose a copy: the queued entry stays raw so a retry still edits
+ // and re-composes the user's text, and the chip (below) still shows
+ // what they typed rather than the composed payload.
+ let mut composed = entry.action.clone();
+ if let Err(error) = self
+ .compose_action(&mut composed, entry.actor.as_ref(), entry.announce.as_ref())
+ .await
+ {
+ self.queues.requeue_front(session_id, entry);
+ return Err(error);
+ }
+
+ if !entry.announced {
+ let announcement = match self
+ .announcement(
+ session_id,
+ &entry.action,
+ entry.actor.as_ref(),
+ entry.announce.clone(),
+ )
+ .await
+ {
+ Ok(announcement) => announcement,
+ Err(error) => {
+ self.queues.requeue_front(session_id, entry);
+ return Err(error);
+ }
+ };
+ if let Some(announcement) = announcement {
+ if let Err(error) = self.announcer.announce(announcement).await {
+ self.queues.requeue_front(session_id, entry);
+ return Err(error);
+ }
+ entry.announced = true;
+ }
+ }
+
+ let command = DeliverAction {
+ id: entry.action_id,
+ action: composed,
+ actor: entry.actor.clone(),
+ announce: entry.announce.clone(),
+ };
+ match self.deliver(session_id, command).await {
+ Ok(()) => {
+ self.busy.insert(session_id, ());
+ Ok(())
+ }
+ Err(error) => {
+ self.queues.requeue_front(session_id, entry);
+ Err(error)
+ }
+ }
+ }
+}
+
+/// Map a queue refusal into the session vocabulary, which is where the
+/// control surface's callers read their errors from.
+pub(super) fn queue_result<T>(
+ result: std::result::Result<T, QueueError>,
+ session_id: AgentSessionId,
+) -> Result<T> {
+ result.map_err(|error| {
+ HarnessError::Session(match error {
+ QueueError::NotFound => AgentSessionError::QueuedControlNotFound,
+ QueueError::NotEditable => AgentSessionError::QueuedControlNotEditable,
+ QueueError::Full => AgentSessionError::ControlQueueFull(session_id),
+ })
+ })
+}
+
+pub(super) async fn run_session_worker<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+>(
+ session_id: AgentSessionId,
+ inner: Arc<
+ AgentHarnessInner<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ >,
+ >,
+ mut receiver: mpsc::UnboundedReceiver<QueuedCommand>,
+) where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+ PromptContext: ChannelPromptContext,
+ PromptComposer: AgentPromptComposer,
+ Egress: SandboxEgressProvisioner,
+{
+ while let Some(queued) = receiver.recv().await {
+ let QueuedCommand {
+ command,
+ completed,
+ span,
+ route,
+ } = queued;
+ let result = if route {
+ inner
+ .route_then_execute(session_id, command)
+ .instrument(span)
+ .await
+ } else {
+ inner.execute(session_id, command).instrument(span).await
+ };
+ let _ = completed.send(result);
+ }
+}
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index df2a33d888..dc9f2ee10b 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -17,7 +17,7 @@ use agent_runtime_protocol::domain::{
};
use agent_session::PROTOCOL_VERSION;
use agent_session::domain::model::{
- AgentSessionId, CreateAgentSessionParams, Message, SandboxSize,
+ AgentMcpServers, AgentSessionId, CreateAgentSessionParams, Message, SandboxSize,
};
use agent_session::domain::ports::{
AgentSessionLogRepo as _, AgentSessionNotificationRecipient as _, AgentSessionRepo as _,
@@ -78,6 +78,7 @@ fn open_command() -> OpenSession {
model: "agent-model".to_owned(),
harness: "opencode".to_owned(),
instructions: String::new(),
+ mcp_servers: AgentMcpServers::OwnerConnections,
},
origin: MentionOrigin {
channel_id: macro_uuid::generate_uuid_v7(),
@@ -415,6 +416,7 @@ async fn disconnected_session(
workspace: "/workspace".to_owned(),
sandbox_size: agent_session::domain::model::SandboxSize::Default,
instructions: None,
+ mcp_servers: Default::default(),
egress_token_hash: None,
},
)
@@ -489,6 +491,42 @@ async fn open_creates_announces_and_delivers_the_mention() {
);
}
+/// The agent's MCP selection is snapshotted onto the session row at open, so
+/// the proxy enforces exactly what this attach advertised for as long as the
+/// session lives, whatever the agent is edited to later.
+#[tokio::test]
+async fn open_snapshots_the_agents_mcp_selection_onto_the_session() {
+ let (service, repo, containers, _announcer, _runtimes) = harness();
+ let mut command = open_command();
+ let selection = AgentMcpServers::Selected {
+ servers: vec![agent_session::domain::model::AgentMcpServer {
+ app_slug: "linear".to_owned(),
+ server_name: "Linear".to_owned(),
+ }],
+ };
+ command.runtime.mcp_servers = selection.clone();
+ let id = AgentSessionId::new();
+
+ let open = service.execute(id, HarnessCommand::Open(command));
+ let drive = async {
+ loop {
+ if containers.spawned() == 1 {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ let container = containers
+ .container(session_of(&containers))
+ .expect("the spawned container is findable");
+ complete_handshake(&container).await;
+ };
+ let (opened, ()) = tokio::join!(open, drive);
+ opened.expect("open should succeed");
+
+ let session = repo.get(id).await.expect("the session row exists");
+ assert_eq!(session.mcp_servers, selection);
+}
+
#[tokio::test]
async fn context_failure_still_calls_composer_with_empty_messages_and_delivers() {
let composer = PromptComposerMock::default();
diff --git a/crates/agent_harness/src/inbound/kafka/test.rs b/crates/agent_harness/src/inbound/kafka/test.rs
index fcd57d2df0..251ed0fcbb 100644
--- a/crates/agent_harness/src/inbound/kafka/test.rs
+++ b/crates/agent_harness/src/inbound/kafka/test.rs
@@ -1,5 +1,5 @@
use agent_runtime_protocol::domain::action::AgentAction;
-use agent_session::domain::model::AgentSessionId;
+use agent_session::domain::model::{AgentMcpServers, AgentSessionId};
use agent_trigger::domain::broker_events::{
AgentBotMentionedEvent, AgentTriggerTopicEvent, ChannelEventMetadata, ChannelKind,
ExistingAgentSessionEvent, NewAgentSessionEvent,
@@ -27,6 +27,7 @@ fn runtime(kind: AgentKind) -> Option<AgentRuntimeConfig> {
}
.to_owned(),
instructions: "configured instructions".to_owned(),
+ mcp_servers: AgentMcpServers::OwnerConnections,
})
}
diff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rs
index 40a9b3e00c..547d4b9bfa 100644
--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs
+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs
@@ -77,6 +77,7 @@ impl AgentSessionRepo for StubSessions {
name: DEFAULT_AGENT_SESSION_NAME.to_owned(),
sandbox_size: SandboxSize::Default,
instructions: None,
+ mcp_servers: Default::default(),
acp_session_id: self
.acp_session_id
.lock()
diff --git a/crates/agent_harness/src/outbound/egress.rs b/crates/agent_harness/src/outbound/egress.rs
index 797ab5e4b0..148c1d0293 100644
--- a/crates/agent_harness/src/outbound/egress.rs
+++ b/crates/agent_harness/src/outbound/egress.rs
@@ -18,7 +18,7 @@ use url::Url;
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::{ProvisionedEgress, SandboxEgress};
use crate::domain::ports::SandboxEgressProvisioner;
-use agent_session::domain::model::AgentSessionId;
+use agent_session::domain::model::{AgentMcpServers, AgentSessionId};
#[cfg(test)]
mod test;
@@ -47,35 +47,62 @@ where
}
}
- /// The slugs of the owner's enabled Pipedream connections, verbatim.
+ /// The slugs to advertise for one session, verbatim.
///
/// `app_slug`, exactly as the proxy resolves it - the same value at both
/// ends by equality is what makes a server entry dialable, and there is
/// no derivation for the two to disagree over. Macro's own server is not
- /// in the list: every session has it, on its own route. An app the owner
- /// turned off is left out here as well as refused by the proxy: an agent
- /// that can see a server in its list will try it, and a tool call that
- /// always fails is worse than a tool that is absent.
- async fn slugs(&self, owner: &MacroUserIdStr<'static>) -> Result<Vec<McpServerSlug>> {
- let records = self.connections.list(owner).await.map_err(|error| {
- HarnessError::Egress(rootcause::report!(
- "could not list Pipedream connections: {error:?}"
- ))
- })?;
-
- let slugs: Vec<McpServerSlug> = records
+ /// in the list: every session has it, on its own route.
+ ///
+ /// Under [`AgentMcpServers::OwnerConnections`] an app the owner turned
+ /// off is left out here as well as refused by the proxy: an agent that
+ /// can see a server in its list will try it, and a call the proxy answers
+ /// with a bare "no such server" is worse than a tool that is absent.
+ ///
+ /// Under [`AgentMcpServers::Selected`] the agent's list is advertised
+ /// whole, including apps the owner has not connected. That is deliberate,
+ /// and the reason the proxy answers those differently: a call to a
+ /// selected-but-unconnected app comes back as a tool result that says so
+ /// and names the fix, which the model can act on, and the moment the
+ /// owner connects the app the same advertised server starts working with
+ /// nothing re-attached.
+ async fn advertised(
+ &self,
+ owner: &MacroUserIdStr<'static>,
+ selection: &AgentMcpServers,
+ ) -> Result<Vec<McpServerSlug>> {
+ let raw: Vec<String> = match selection {
+ AgentMcpServers::OwnerConnections => self
+ .connections
+ .list(owner)
+ .await
+ .map_err(|error| {
+ HarnessError::Egress(rootcause::report!(
+ "could not list Pipedream connections: {error:?}"
+ ))
+ })?
+ .into_iter()
+ .filter(|record| record.enabled)
+ .map(|record| record.app_slug)
+ .collect(),
+ AgentMcpServers::Selected { servers } => servers
+ .iter()
+ .map(|server| server.app_slug.clone())
+ .collect(),
+ };
+
+ let slugs: Vec<McpServerSlug> = raw
.into_iter()
- .filter(|record| record.enabled)
- .filter_map(|record| {
- let slug = McpServerSlug::parse(&record.app_slug);
+ .filter_map(|app_slug| {
+ let slug = McpServerSlug::parse(&app_slug);
if slug.is_none() {
// An app slug the strict parse refuses could never be
// dialed - the proxy would refuse the same path segment -
// so leaving it out is the only honest rendering.
tracing::warn!(
%owner,
- app_slug = %record.app_slug,
- "a Pipedream connection's app slug is not a valid path segment; skipped"
+ %app_slug,
+ "an MCP server's app slug is not a valid path segment; skipped"
);
}
slug
@@ -83,7 +110,8 @@ where
.collect();
tracing::debug!(
mcp_servers = slugs.len(),
- "advertising the owner's connected MCP servers"
+ scope = selection.scope_str(),
+ "advertising MCP servers"
);
Ok(slugs)
}
@@ -99,6 +127,7 @@ where
session: AgentSessionId,
owner: &MacroUserIdStr<'static>,
repo_url: &str,
+ selection: &AgentMcpServers,
) -> Result<ProvisionedEgress> {
// Validated even though nothing here uses it: it is the deployment's
// repository URL, and a session whose git traffic could never resolve
@@ -112,7 +141,7 @@ where
sandbox: SandboxEgress {
base_url: self.base_url.clone(),
session_token: token.as_str().to_owned(),
- mcp_servers: self.slugs(owner).await?,
+ mcp_servers: self.advertised(owner, selection).await?,
},
})
}
@@ -122,11 +151,12 @@ where
&self,
owner: &MacroUserIdStr<'static>,
session_token: String,
+ selection: &AgentMcpServers,
) -> Result<SandboxEgress> {
Ok(SandboxEgress {
base_url: self.base_url.clone(),
session_token,
- mcp_servers: self.slugs(owner).await?,
+ mcp_servers: self.advertised(owner, selection).await?,
})
}
}
diff --git a/crates/agent_harness/src/outbound/egress/test.rs b/crates/agent_harness/src/outbound/egress/test.rs
index bbdcab2cbc..a60e4a5ca6 100644
--- a/crates/agent_harness/src/outbound/egress/test.rs
+++ b/crates/agent_harness/src/outbound/egress/test.rs
@@ -1,4 +1,5 @@
use super::*;
+use agent_session::domain::model::AgentMcpServer;
fn slug(name: &str) -> McpServerSlug {
McpServerSlug::parse(name).expect("a valid app slug")
@@ -97,6 +98,7 @@ async fn lists_enabled_app_slugs_verbatim() {
AgentSessionId::new(),
&MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),
"https://github.com/macro-inc/macro",
+ &AgentMcpServers::OwnerConnections,
)
.await
.expect("provisioned");
@@ -123,6 +125,7 @@ async fn restore_wraps_an_existing_token_in_a_fresh_listing() {
.restore(
&MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),
"already-minted-token".to_owned(),
+ &AgentMcpServers::OwnerConnections,
)
.await
.expect("restored");
@@ -136,6 +139,87 @@ async fn restore_wraps_an_existing_token_in_a_fresh_listing() {
assert_eq!(slugs, ["linear"]);
}
+fn selected(slugs: &[&str]) -> AgentMcpServers {
+ AgentMcpServers::Selected {
+ servers: slugs
+ .iter()
+ .map(|slug| AgentMcpServer {
+ app_slug: (*slug).to_owned(),
+ server_name: (*slug).to_owned(),
+ })
+ .collect(),
+ }
+}
+
+/// A selected list is advertised whole, in the agent's order, whatever the
+/// owner has connected: an unconnected app is still dialable, because the
+/// proxy answers it with a "not connected" tool result rather than refusing
+/// it, and a connected-but-unselected app is not offered at all.
+#[tokio::test]
+async fn a_selected_list_is_advertised_regardless_of_connections() {
+ let provisioner = EgressProvisioner::new(
+ Arc::new(FixedConnections(vec![
+ connection("datadog", true),
+ connection("linear", false),
+ ])),
+ "https://egress.macro.com",
+ );
+
+ let provisioned = provisioner
+ .provision(
+ AgentSessionId::new(),
+ &MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),
+ "https://github.com/macro-inc/macro",
+ &selected(&["notion", "linear", "Not A Slug!"]),
+ )
+ .await
+ .expect("provisioned");
+
+ let slugs: Vec<String> = provisioned
+ .sandbox
+ .mcp_servers
+ .iter()
+ .map(ToString::to_string)
+ .collect();
+ assert_eq!(slugs, ["notion", "linear"]);
+
+ let restored = provisioner
+ .restore(
+ &MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),
+ "already-minted-token".to_owned(),
+ &selected(&["notion"]),
+ )
+ .await
+ .expect("restored");
+ let slugs: Vec<String> = restored
+ .mcp_servers
+ .iter()
+ .map(ToString::to_string)
+ .collect();
+ assert_eq!(slugs, ["notion"]);
+}
+
+/// An explicitly empty selection is the agent author's choice: nothing of the
+/// owner's is offered in its place.
+#[tokio::test]
+async fn an_empty_selection_offers_nothing_of_the_owners() {
+ let provisioner = EgressProvisioner::new(
+ Arc::new(FixedConnections(vec![connection("datadog", true)])),
+ "https://egress.macro.com",
+ );
+
+ let provisioned = provisioner
+ .provision(
+ AgentSessionId::new(),
+ &MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),
+ "https://github.com/macro-inc/macro",
+ &selected(&[]),
+ )
+ .await
+ .expect("provisioned");
+ assert!(provisioned.sandbox.mcp_servers.is_empty());
+}
+
fn egress(slugs: &[&str]) -> SandboxEgress {
SandboxEgress {
base_url: "https://egress.macro.com".to_owned(),
diff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rs
index 66e0375df3..c67665b610 100644
--- a/crates/agent_harness/src/outbound/routing/test.rs
+++ b/crates/agent_harness/src/outbound/routing/test.rs
@@ -117,6 +117,7 @@ impl AgentSessionRepo for FixedBotSessions {
name: DEFAULT_AGENT_SESSION_NAME.to_owned(),
sandbox_size: SandboxSize::Default,
instructions: None,
+ mcp_servers: Default::default(),
acp_session_id: None,
external: None,
status: SessionStatus::NoMessages,
diff --git a/crates/agent_harness/src/testing/helpers/egress.rs b/crates/agent_harness/src/testing/helpers/egress.rs
index 7885349269..8e51a6866c 100644
--- a/crates/agent_harness/src/testing/helpers/egress.rs
+++ b/crates/agent_harness/src/testing/helpers/egress.rs
@@ -2,18 +2,22 @@
use std::sync::{Arc, Mutex};
-use agent_session::domain::model::AgentSessionId;
+use agent_session::domain::model::{AgentMcpServers, AgentSessionId};
use macro_user_id::user_id::MacroUserIdStr;
use crate::domain::error::Result;
use crate::domain::model::{ProvisionedEgress, SandboxEgress};
use crate::domain::ports::SandboxEgressProvisioner;
+/// One recorded provisioning: session, owner, repository URL, and the MCP
+/// selection it was asked to advertise.
+pub type RecordedProvisioning = (AgentSessionId, String, String, AgentMcpServers);
+
/// A [`SandboxEgressProvisioner`] that records who it was asked for and hands
/// back a fixed environment. Cloning shares one record.
#[derive(Clone, Default)]
pub struct EgressProvisionerMock {
- provisioned: Arc<Mutex<Vec<(AgentSessionId, String, String)>>>,
+ provisioned: Arc<Mutex<Vec<RecordedProvisioning>>>,
}
impl EgressProvisionerMock {
@@ -23,9 +27,10 @@ impl EgressProvisionerMock {
Self::default()
}
- /// Every provisioning recorded, as session, owner, and repository URL.
+ /// Every provisioning recorded, as session, owner, repository URL, and
+ /// the MCP selection it was asked to advertise.
#[must_use]
- pub fn provisioned(&self) -> Vec<(AgentSessionId, String, String)> {
+ pub fn provisioned(&self) -> Vec<RecordedProvisioning> {
self.provisioned
.lock()
.expect("egress mock lock should not be poisoned")
@@ -39,11 +44,17 @@ impl SandboxEgressProvisioner for EgressProvisionerMock {
session: AgentSessionId,
owner: &MacroUserIdStr<'static>,
repo_url: &str,
+ selection: &AgentMcpServers,
) -> Result<ProvisionedEgress> {
self.provisioned
.lock()
.expect("egress mock lock should not be poisoned")
- .push((session, owner.to_string(), repo_url.to_owned()));
+ .push((
+ session,
+ owner.to_string(),
+ repo_url.to_owned(),
+ selection.clone(),
+ ));
Ok(ProvisionedEgress {
sandbox: test_egress(),
@@ -55,6 +66,7 @@ impl SandboxEgressProvisioner for EgressProvisionerMock {
&self,
_owner: &MacroUserIdStr<'static>,
session_token: String,
+ _selection: &AgentMcpServers,
) -> Result<SandboxEgress> {
Ok(SandboxEgress {
session_token,
diff --git a/crates/agent_inmem/Cargo.toml b/crates/agent_inmem/Cargo.toml
index 36bf9c041b..3ed8f55ccb 100644
--- a/crates/agent_inmem/Cargo.toml
+++ b/crates/agent_inmem/Cargo.toml
@@ -6,24 +6,36 @@ version = "0.1.0"
[dependencies]
agent = { path = "../agent" }
+# The egress proxy's domain service, driven in-process: the same verification,
+# resolution and stamping a sandbox reaches over the wire, minus the wire.
+agent_egress = { path = "../agent_egress" }
agent-client-protocol = { workspace = true }
agent_runtime_protocol = { path = "../agent_runtime_protocol" }
agent_session = { path = "../agent_session" }
ai_tools = { path = "../ai_tools" }
ai_toolset = { path = "../ai_toolset" }
ai_usage = { path = "../ai_usage" }
+bytes = { workspace = true }
dashmap = { workspace = true }
futures = { workspace = true }
macro_user_id = { path = "../macro_user_id" }
+http = { workspace = true }
+http-body-util = { workspace = true }
macro_uuid = { path = "../macro_uuid" }
+mcp_select = { path = "../mcp_select" }
+mcp_toolset = { path = "../mcp_toolset" }
memory = { path = "../memory" }
prompt = { path = "../prompt" }
+rmcp = { workspace = true, features = ["client", "transport-streamable-http-client"] }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
+sse-stream = { workspace = true }
+thiserror = { workspace = true }
tokio = { workspace = true, features = ["sync", "rt", "time", "macros"] }
tokio-util = { workspace = true }
tracing = { workspace = true }
+url = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
diff --git a/crates/agent_inmem/src/domain/agent.rs b/crates/agent_inmem/src/domain/agent.rs
index db64a28587..8f2e7d6d45 100644
--- a/crates/agent_inmem/src/domain/agent.rs
+++ b/crates/agent_inmem/src/domain/agent.rs
@@ -31,7 +31,10 @@ use macro_user_id::user_id::MacroUserIdStr;
use tokio_util::sync::CancellationToken;
use crate::domain::engine::{TurnEngine, TurnRequest};
+use crate::domain::mcp::{DynMcpToolConnector, dialable_servers};
use crate::domain::session::{HistoryEntry, SessionStore, messages_for_turn};
+use agent_client_protocol::schema::v1::McpServer as AcpMcpServer;
+use mcp_toolset::RemoteMcpToolSet;
#[cfg(test)]
mod test;
@@ -77,9 +80,33 @@ pub struct AgentState {
/// Serializes turns: the client may queue prompts, the engine runs one at
/// a time.
pub turn_lock: tokio::sync::Mutex<()>,
+ /// Dials the MCP servers `session/new` and `session/resume` hand over.
+ pub mcp: Arc<dyn DynMcpToolConnector>,
+ /// The tools of those servers, once dialed; `None` until then or when
+ /// there were none.
+ pub mcp_tools: Mutex<Option<RemoteMcpToolSet>>,
}
impl AgentState {
+ /// Dial the servers a session request carried and keep their tools for
+ /// every turn that follows. Done at `session/new`/`session/resume`, the
+ /// same moment a sandboxed harness connects its servers, so the first
+ /// turn already has them.
+ async fn connect_mcp(&self, servers: Vec<AcpMcpServer>) {
+ let tools = self.mcp.connect_dyn(dialable_servers(servers)).await;
+ *self
+ .mcp_tools
+ .lock()
+ .expect("mcp tools lock should not be poisoned") = tools;
+ }
+
+ fn current_mcp_tools(&self) -> Option<RemoteMcpToolSet> {
+ self.mcp_tools
+ .lock()
+ .expect("mcp tools lock should not be poisoned")
+ .clone()
+ }
+
fn expect_session(&self, requested: &SessionId) -> Result<(), AcpError> {
let matches = self
.store
@@ -184,10 +211,11 @@ pub async fn serve(state: Arc<AgentState>, acp: AcpChannel) -> Result<(), AcpErr
.on_receive_request(
{
let state = Arc::clone(&state);
- async move |_request: NewSessionRequest, responder, _connection| {
+ async move |request: NewSessionRequest, responder, _connection| {
let state = Arc::clone(&state);
let acp_id = SessionId::new(macro_uuid::generate_uuid_v7().to_string());
state.bind_acp_session(acp_id.clone(), false);
+ state.connect_mcp(request.mcp_servers).await;
responder.respond(NewSessionResponse::new(acp_id))
}
},
@@ -203,6 +231,7 @@ pub async fn serve(state: Arc<AgentState>, acp: AcpChannel) -> Result<(), AcpErr
// attach replayed the frame log back into it (see
// `domain::replay`).
state.bind_acp_session(request.session_id, true);
+ state.connect_mcp(request.mcp_servers).await;
responder.respond(ResumeSessionResponse::new())
}
},
@@ -310,6 +339,7 @@ async fn run_turn(
model,
instructions,
messages,
+ mcp_tools: state.current_mcp_tools(),
cancel: cancel.clone(),
});
diff --git a/crates/agent_inmem/src/domain/agent/test.rs b/crates/agent_inmem/src/domain/agent/test.rs
index 24338058f3..26e43cd66e 100644
--- a/crates/agent_inmem/src/domain/agent/test.rs
+++ b/crates/agent_inmem/src/domain/agent/test.rs
@@ -61,6 +61,8 @@ where
store,
active_cancel: std::sync::Mutex::new(Vec::new()),
turn_lock: tokio::sync::Mutex::new(()),
+ mcp: Arc::new(crate::domain::mcp::NoMcpServers),
+ mcp_tools: std::sync::Mutex::new(None),
});
let (client_channel, agent_channel) = AcpChannel::duplex();
@@ -353,3 +355,85 @@ async fn a_prompt_for_an_unknown_session_is_refused() {
})
.await;
}
+
+/// Records the servers it was asked to dial and dials none of them.
+struct SpyConnector {
+ asked: std::sync::Mutex<Vec<Vec<String>>>,
+}
+
+impl crate::domain::mcp::McpToolConnector for Arc<SpyConnector> {
+ async fn connect(
+ &self,
+ servers: Vec<agent_client_protocol::schema::v1::McpServerHttp>,
+ ) -> Option<mcp_toolset::RemoteMcpToolSet> {
+ self.asked
+ .lock()
+ .expect("asked lock")
+ .push(servers.into_iter().map(|server| server.name).collect());
+ None
+ }
+}
+
+/// The servers `session/new` carries are dialed then and there, minus Macro's
+/// own, whose tools this runtime already has natively.
+#[tokio::test]
+async fn session_new_dials_the_advertised_servers_except_macros_own() {
+ use agent_client_protocol::schema::v1::{HttpHeader, McpServer as AcpMcpServer, McpServerHttp};
+
+ let spy = Arc::new(SpyConnector {
+ asked: std::sync::Mutex::new(Vec::new()),
+ });
+ let store = Arc::new(SessionStore::new());
+ let session_id = AgentSessionId::new();
+ store.insert(
+ session_id,
+ crate::domain::session::SessionState::new("test-model".into()),
+ );
+ let state = Arc::new(AgentState {
+ session_id,
+ owner: MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),
+ engine: Arc::new(ScriptedEngine::new(Vec::new())),
+ store,
+ active_cancel: std::sync::Mutex::new(Vec::new()),
+ turn_lock: tokio::sync::Mutex::new(()),
+ mcp: Arc::new(Arc::clone(&spy)),
+ mcp_tools: std::sync::Mutex::new(None),
+ });
+ let (client_channel, agent_channel) = AcpChannel::duplex();
+ let agent = tokio::spawn(serve(state, agent_channel));
+
+ let servers = ["macro", "linear", "notion"]
+ .into_iter()
+ .map(|name| {
+ AcpMcpServer::Http(
+ McpServerHttp::new(name, format!("https://egress.test/mcp/{name}")).headers(vec![
+ HttpHeader::new("Authorization", "Bearer session-token"),
+ ]),
+ )
+ })
+ .collect::<Vec<_>>();
+ Client
+ .builder()
+ .connect_with(
+ client_channel,
+ async move |connection: ConnectionTo<Agent>| {
+ connection
+ .send_request(InitializeRequest::new(ProtocolVersion::V1))
+ .block_task()
+ .await?;
+ connection
+ .send_request(NewSessionRequest::new("/").mcp_servers(servers))
+ .block_task()
+ .await?;
+ Ok(())
+ },
+ )
+ .await
+ .expect("the scripted client should run clean");
+ agent.abort();
+
+ assert_eq!(
+ *spy.asked.lock().expect("asked lock"),
+ vec![vec!["linear".to_owned(), "notion".to_owned()]]
+ );
+}
diff --git a/crates/agent_inmem/src/domain/engine.rs b/crates/agent_inmem/src/domain/engine.rs
index 1e6f7890bb..698c7bd8b5 100644
--- a/crates/agent_inmem/src/domain/engine.rs
+++ b/crates/agent_inmem/src/domain/engine.rs
@@ -3,6 +3,7 @@
use agent::types::ChatMessage;
use agent::{AgentError, StreamPart};
use macro_user_id::user_id::MacroUserIdStr;
+use mcp_toolset::RemoteMcpToolSet;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
@@ -20,6 +21,9 @@ pub struct TurnRequest {
/// The full conversation, oldest first, ending with the prompt being
/// answered.
pub messages: Vec<ChatMessage>,
+ /// Tools of the MCP servers the session was handed, composed next to the
+ /// native Macro tools. `None` when the session has none.
+ pub mcp_tools: Option<RemoteMcpToolSet>,
/// Cancelling this token stops the turn; the stream ends after the
/// engine has drained cooperatively.
pub cancel: CancellationToken,
diff --git a/crates/agent_inmem/src/domain/mcp.rs b/crates/agent_inmem/src/domain/mcp.rs
new file mode 100644
index 0000000000..8569349b4e
--- /dev/null
+++ b/crates/agent_inmem/src/domain/mcp.rs
@@ -0,0 +1,85 @@
+//! The MCP servers an in-process session is handed, and how it reaches them.
+//!
+//! Every runtime the harness manages gets its MCP servers the same way: as
+//! HTTP entries in `session/new` (and again on `session/resume`), each one an
+//! egress-proxy URL carrying the session token. A sandboxed harness dials
+//! those from its container; this runtime dials them from this process. The
+//! traffic is the same, and so is what the proxy does with it: resolve the
+//! app against the session owner's own connections, or answer a call to an
+//! app they have not connected with a result the model can act on.
+
+use agent_client_protocol::schema::v1::{McpServer as AcpMcpServer, McpServerHttp};
+use mcp_toolset::RemoteMcpToolSet;
+
+#[cfg(test)]
+mod test;
+
+/// The name the harness gives Macro's own MCP server in the ACP list.
+///
+/// Restated from `agent_harness::MACRO_MCP_NAME` rather than imported - this
+/// crate is a runtime the harness drives, not a dependant of it - and pinned
+/// equal by a test in the composition root, which sees both. Macro's tools are
+/// native here (see [`ai_tools::all_tools`]), so the entry is skipped: dialing
+/// it would give the model every Macro tool twice.
+pub const MACRO_MCP_NAME: &str = "macro";
+
+/// The servers this runtime should dial out of an ACP server list: HTTP
+/// entries other than Macro's own. SSE and stdio entries are not something an
+/// in-process runtime can serve and are dropped with a warning.
+pub fn dialable_servers(servers: Vec<AcpMcpServer>) -> Vec<McpServerHttp> {
+ servers
+ .into_iter()
+ .filter_map(|server| match server {
+ AcpMcpServer::Http(http) if http.name == MACRO_MCP_NAME => None,
+ AcpMcpServer::Http(http) => Some(http),
+ other => {
+ tracing::warn!(
+ server = ?other,
+ "an in-process session can only dial HTTP MCP servers; skipped"
+ );
+ None
+ }
+ })
+ .collect()
+}
+
+/// Opens sessions on the HTTP MCP servers a session was handed and builds the
+/// toolset over them.
+///
+/// A port because it is transport work: the production adapter speaks
+/// streamable HTTP through the egress proxy, tests hand back nothing.
+pub trait McpToolConnector: Send + Sync + 'static {
+ /// Connect to every server, skipping any that fail, and return the tools
+ /// found. `None` when no server yielded any tool.
+ fn connect(
+ &self,
+ servers: Vec<McpServerHttp>,
+ ) -> impl Future<Output = Option<RemoteMcpToolSet>> + Send;
+}
+
+/// Erased form of [`McpToolConnector`] for storage on the agent state.
+pub trait DynMcpToolConnector: Send + Sync + 'static {
+ /// See [`McpToolConnector::connect`].
+ fn connect_dyn(
+ &self,
+ servers: Vec<McpServerHttp>,
+ ) -> std::pin::Pin<Box<dyn Future<Output = Option<RemoteMcpToolSet>> + Send + '_>>;
+}
+
+impl<C: McpToolConnector> DynMcpToolConnector for C {
+ fn connect_dyn(
+ &self,
+ servers: Vec<McpServerHttp>,
+ ) -> std::pin::Pin<Box<dyn Future<Output = Option<RemoteMcpToolSet>> + Send + '_>> {
+ Box::pin(self.connect(servers))
+ }
+}
+
+/// A connector for deployments and tests that hand the runtime no servers.
+pub struct NoMcpServers;
+
+impl McpToolConnector for NoMcpServers {
+ async fn connect(&self, _servers: Vec<McpServerHttp>) -> Option<RemoteMcpToolSet> {
+ None
+ }
+}
diff --git a/crates/agent_inmem/src/domain/mcp/test.rs b/crates/agent_inmem/src/domain/mcp/test.rs
new file mode 100644
index 0000000000..20d201044e
--- /dev/null
+++ b/crates/agent_inmem/src/domain/mcp/test.rs
@@ -0,0 +1,39 @@
+use super::*;
+use agent_client_protocol::schema::v1::{HttpHeader, McpServerStdio};
+
+fn http(name: &str) -> AcpMcpServer {
+ AcpMcpServer::Http(
+ McpServerHttp::new(name, format!("https://egress.test/mcp/{name}")).headers(vec![
+ HttpHeader::new("Authorization", "Bearer session-token"),
+ ]),
+ )
+}
+
+#[test]
+fn macros_own_server_is_never_dialed() {
+ let dialable = dialable_servers(vec![http("macro"), http("linear"), http("notion")]);
+ let names: Vec<&str> = dialable.iter().map(|server| server.name.as_str()).collect();
+ assert_eq!(names, ["linear", "notion"]);
+}
+
+#[test]
+fn only_http_servers_are_dialable() {
+ let dialable = dialable_servers(vec![
+ AcpMcpServer::Stdio(McpServerStdio::new("local", "some-binary")),
+ http("linear"),
+ ]);
+ let names: Vec<&str> = dialable.iter().map(|server| server.name.as_str()).collect();
+ assert_eq!(names, ["linear"]);
+}
+
+#[test]
+fn dialable_servers_keep_their_headers() {
+ let dialable = dialable_servers(vec![http("linear")]);
+ let headers: Vec<(&str, &str)> = dialable[0]
+ .headers
+ .iter()
+ .map(|header| (header.name.as_str(), header.value.as_str()))
+ .collect();
+ assert_eq!(headers, [("Authorization", "Bearer session-token")]);
+ assert_eq!(dialable[0].url, "https://egress.test/mcp/linear");
+}
diff --git a/crates/agent_inmem/src/domain/mod.rs b/crates/agent_inmem/src/domain/mod.rs
index c81f34bf3a..47d98673dd 100644
--- a/crates/agent_inmem/src/domain/mod.rs
+++ b/crates/agent_inmem/src/domain/mod.rs
@@ -3,5 +3,6 @@
pub mod agent;
pub mod engine;
+pub mod mcp;
pub mod replay;
pub mod session;
diff --git a/crates/agent_inmem/src/outbound/acp_mcp.rs b/crates/agent_inmem/src/outbound/acp_mcp.rs
new file mode 100644
index 0000000000..71cab72498
--- /dev/null
+++ b/crates/agent_inmem/src/outbound/acp_mcp.rs
@@ -0,0 +1,126 @@
+//! Dialing the HTTP MCP servers a session was handed over ACP.
+
+use std::collections::HashMap;
+
+use agent_client_protocol::schema::v1::McpServerHttp;
+use http::header::{AUTHORIZATION, HeaderName, HeaderValue};
+use mcp_toolset::{ConnectedServer, RemoteMcpToolSet, client_info};
+use rmcp::ServiceExt as _;
+use rmcp::transport::StreamableHttpClientTransport;
+use rmcp::transport::streamable_http_client::{
+ StreamableHttpClient, StreamableHttpClientTransportConfig,
+};
+
+use crate::domain::mcp::McpToolConnector;
+
+#[cfg(test)]
+mod test;
+
+/// Where one advertised header goes on the rmcp transport.
+#[derive(Debug, PartialEq, Eq)]
+enum HeaderPlacement {
+ /// `Authorization: Bearer <token>`: rmcp takes the bare token and adds the
+ /// scheme itself, so the scheme must come off here or the proxy sees
+ /// `Bearer Bearer <token>` and knows no such session.
+ BearerToken(String),
+ /// Anything else, sent verbatim.
+ Custom(HeaderName, HeaderValue),
+}
+
+/// Decide how an ACP `HttpHeader` reaches the wire. `None` when the name or
+/// value is not a valid header.
+fn place_header(name: &str, value: &str) -> Option<HeaderPlacement> {
+ let header_name = HeaderName::from_bytes(name.as_bytes()).ok()?;
+ if header_name == AUTHORIZATION {
+ let mut parts = value.splitn(2, ' ');
+ if let (Some(scheme), Some(token)) = (parts.next(), parts.next())
+ && scheme.eq_ignore_ascii_case("bearer")
+ {
+ return Some(HeaderPlacement::BearerToken(token.trim().to_owned()));
+ }
+ }
+ let header_value = HeaderValue::from_str(value).ok()?;
+ Some(HeaderPlacement::Custom(header_name, header_value))
+}
+
+/// [`McpToolConnector`] over rmcp's streamable-HTTP client.
+///
+/// Each entry is dialed exactly as handed over: its URL is the egress proxy
+/// and its `Authorization` header is the session token, so this process holds
+/// no upstream credential any more than a sandbox does. What carries the
+/// request is the `Client` - in production
+/// [`EgressMcpClient`](super::egress_mcp::EgressMcpClient), which hands it
+/// to the proxy's service without a socket.
+#[derive(Clone)]
+pub struct AcpMcpConnector<Client> {
+ client: Client,
+}
+
+impl<Client> AcpMcpConnector<Client>
+where
+ Client: StreamableHttpClient + Send + Sync,
+{
+ /// A connector sharing one client across every server it dials.
+ pub fn new(client: Client) -> Self {
+ Self { client }
+ }
+
+ async fn connect_one(&self, server: McpServerHttp) -> Option<ConnectedServer> {
+ let mut config = StreamableHttpClientTransportConfig::with_uri(server.url.clone());
+ let mut custom = HashMap::new();
+ for header in &server.headers {
+ match place_header(&header.name, &header.value) {
+ Some(HeaderPlacement::BearerToken(token)) => {
+ config = config.auth_header(token);
+ }
+ Some(HeaderPlacement::Custom(name, value)) => {
+ custom.insert(name, value);
+ }
+ None => {
+ tracing::warn!(server = %server.name, header = %header.name, "dropping an invalid header");
+ }
+ }
+ }
+ config.custom_headers = custom;
+
+ let transport = StreamableHttpClientTransport::with_client(self.client.clone(), config);
+ match client_info().serve(transport).await {
+ Ok(client) => Some(ConnectedServer {
+ name: server.name,
+ client,
+ }),
+ Err(error) => {
+ // One server that will not answer must not cost the session
+ // the others, nor the session itself.
+ tracing::warn!(server = %server.name, error = ?error, "failed to connect to an MCP server; skipping it");
+ None
+ }
+ }
+ }
+}
+
+impl<Client> McpToolConnector for AcpMcpConnector<Client>
+where
+ Client: StreamableHttpClient + Send + Sync,
+{
+ #[tracing::instrument(skip_all, fields(servers = servers.len()))]
+ async fn connect(&self, servers: Vec<McpServerHttp>) -> Option<RemoteMcpToolSet> {
+ if servers.is_empty() {
+ return None;
+ }
+ let connected: Vec<ConnectedServer> =
+ futures::future::join_all(servers.into_iter().map(|server| self.connect_one(server)))
+ .await
+ .into_iter()
+ .flatten()
+ .collect();
+ if connected.is_empty() {
+ return None;
+ }
+ let tools = RemoteMcpToolSet::from_connected(connected, None).await;
+ if tools.is_empty() {
+ return None;
+ }
+ Some(tools)
+ }
+}
diff --git a/crates/agent_inmem/src/outbound/acp_mcp/test.rs b/crates/agent_inmem/src/outbound/acp_mcp/test.rs
new file mode 100644
index 0000000000..c152dc3a38
--- /dev/null
+++ b/crates/agent_inmem/src/outbound/acp_mcp/test.rs
@@ -0,0 +1,40 @@
+use super::*;
+
+/// The harness advertises `Authorization: Bearer <session token>`; rmcp wants
+/// the bare token and adds the scheme itself.
+#[test]
+fn a_bearer_authorization_header_becomes_the_bare_token() {
+ assert_eq!(
+ place_header("Authorization", "Bearer session-token"),
+ Some(HeaderPlacement::BearerToken("session-token".to_owned()))
+ );
+ assert_eq!(
+ place_header("authorization", "bearer spaced-token "),
+ Some(HeaderPlacement::BearerToken("spaced-token".to_owned()))
+ );
+}
+
+#[test]
+fn other_headers_are_sent_verbatim() {
+ assert_eq!(
+ place_header("X-Custom", "value"),
+ Some(HeaderPlacement::Custom(
+ HeaderName::from_static("x-custom"),
+ HeaderValue::from_static("value"),
+ ))
+ );
+ // A non-bearer authorization scheme is not something to strip.
+ assert_eq!(
+ place_header("Authorization", "Basic abc"),
+ Some(HeaderPlacement::Custom(
+ AUTHORIZATION,
+ HeaderValue::from_static("Basic abc"),
+ ))
+ );
+}
+
+#[test]
+fn invalid_headers_are_dropped() {
+ assert_eq!(place_header("not a header", "x"), None);
+ assert_eq!(place_header("X-Custom", "line\nbreak"), None);
+}
diff --git a/crates/agent_inmem/src/outbound/egress_mcp.rs b/crates/agent_inmem/src/outbound/egress_mcp.rs
new file mode 100644
index 0000000000..8f45f35603
--- /dev/null
+++ b/crates/agent_inmem/src/outbound/egress_mcp.rs
@@ -0,0 +1,332 @@
+//! rmcp's streamable-HTTP client, served by the egress proxy in-process.
+//!
+//! The sandboxed harnesses reach their MCP servers by dialing the proxy over
+//! the wire. This runtime lives in the same process as the proxy, so it hands
+//! each request straight to the proxy's domain service instead: the same
+//! token check, the same owner resolution, the same credential stamping, the
+//! same answer for an app the owner has not connected - and no loopback
+//! socket, no reachable-from-here base URL, nothing to configure.
+//!
+//! What it is given is still the ACP server list, URLs and all, because that
+//! is what every harness is given. The URL's path names the server and the
+//! `Authorization` header carries the session token; both are read here the
+//! way the proxy's router reads them.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use agent_egress::domain::error::EgressError;
+use agent_egress::domain::model::{
+ EgressTarget, McpDestination, ProxyBody, ProxyRequest, ProxyResponse, SessionToken,
+};
+use agent_egress::domain::service::EgressService;
+use bytes::Bytes;
+use futures::StreamExt as _;
+use futures::stream::BoxStream;
+use http::header::{ACCEPT, CONTENT_TYPE};
+use http::{HeaderName, HeaderValue, Method, StatusCode};
+use http_body_util::{BodyExt as _, Empty, Full};
+use rmcp::model::{ClientJsonRpcMessage, JsonRpcMessage, ServerJsonRpcMessage};
+use rmcp::transport::common::http_header::{
+ EVENT_STREAM_MIME_TYPE, HEADER_LAST_EVENT_ID, HEADER_SESSION_ID, JSON_MIME_TYPE,
+};
+use rmcp::transport::streamable_http_client::{
+ SseError, StreamableHttpClient, StreamableHttpError, StreamableHttpPostResponse,
+};
+use sse_stream::{Sse, SseStream};
+
+#[cfg(test)]
+mod test;
+
+/// What stops a request short of the proxy, or the proxy's own refusal.
+#[derive(Debug, thiserror::Error)]
+pub enum EgressCallError {
+ /// The URL does not name a server the proxy serves.
+ #[error("{0} is not an egress MCP server URL")]
+ NotAnEgressUrl(String),
+ /// The server entry carried no session token.
+ #[error("the MCP server entry carries no session token")]
+ NoSessionToken,
+ /// The proxy refused or failed the call.
+ #[error(transparent)]
+ Egress(#[from] EgressError),
+ /// The proxy answered, but its body could not be read.
+ #[error("could not read the proxy's response body: {0}")]
+ Body(String),
+}
+
+type CallError = StreamableHttpError<EgressCallError>;
+
+/// A [`StreamableHttpClient`] that calls the egress service directly.
+///
+/// One `Arc` shared with the proxy's own listener, so the two are the same
+/// service with the same pools, not two configured alike.
+pub struct EgressMcpClient<Egress> {
+ egress: Arc<Egress>,
+}
+
+impl<Egress> EgressMcpClient<Egress> {
+ /// A client over the service the proxy's listener also serves.
+ pub fn new(egress: Arc<Egress>) -> Self {
+ Self { egress }
+ }
+}
+
+// Derived `Clone` would demand `Egress: Clone`, which the service is not.
+impl<Egress> Clone for EgressMcpClient<Egress> {
+ fn clone(&self) -> Self {
+ Self {
+ egress: Arc::clone(&self.egress),
+ }
+ }
+}
+
+/// Where a request is going, read off the pieces rmcp hands over.
+struct Addressed {
+ token: SessionToken,
+ target: EgressTarget,
+}
+
+fn address(uri: &str, auth_header: Option<String>) -> Result<Addressed, CallError> {
+ let url = url::Url::parse(uri).map_err(|_| {
+ StreamableHttpError::Client(EgressCallError::NotAnEgressUrl(uri.to_owned()))
+ })?;
+ let destination = McpDestination::from_path(url.path()).ok_or_else(|| {
+ StreamableHttpError::Client(EgressCallError::NotAnEgressUrl(uri.to_owned()))
+ })?;
+ let token = auth_header
+ .map(SessionToken::new)
+ .ok_or(StreamableHttpError::Client(EgressCallError::NoSessionToken))?;
+ Ok(Addressed {
+ token,
+ target: EgressTarget::McpServer(destination),
+ })
+}
+
+fn empty_body() -> ProxyBody {
+ Empty::new().map_err(|never| match never {}).boxed_unsync()
+}
+
+fn full_body(bytes: Vec<u8>) -> ProxyBody {
+ Full::new(Bytes::from(bytes))
+ .map_err(|never| match never {})
+ .boxed_unsync()
+}
+
+fn build_request(
+ method: Method,
+ uri: &str,
+ session_id: Option<&str>,
+ custom_headers: HashMap<HeaderName, HeaderValue>,
+ body: ProxyBody,
+) -> Result<ProxyRequest, CallError> {
+ let mut builder = http::Request::builder()
+ .method(method)
+ .uri(uri)
+ .header(ACCEPT, [EVENT_STREAM_MIME_TYPE, JSON_MIME_TYPE].join(", "));
+ if let Some(session_id) = session_id {
+ builder = builder.header(HEADER_SESSION_ID, session_id);
+ }
+ for (name, value) in custom_headers {
+ builder = builder.header(name, value);
+ }
+ builder.body(body).map_err(|error| {
+ StreamableHttpError::UnexpectedServerResponse(format!("malformed request: {error}").into())
+ })
+}
+
+fn content_type(response: &ProxyResponse) -> Option<String> {
+ response
+ .headers()
+ .get(CONTENT_TYPE)
+ .map(|value| String::from_utf8_lossy(value.as_bytes()).into_owned())
+}
+
+fn session_id(response: &ProxyResponse) -> Option<String> {
+ response
+ .headers()
+ .get(HEADER_SESSION_ID)
+ .and_then(|value| value.to_str().ok())
+ .map(str::to_owned)
+}
+
+fn is_event_stream(content_type: Option<&str>) -> bool {
+ content_type.is_some_and(|value| value.starts_with(EVENT_STREAM_MIME_TYPE))
+}
+
+fn is_json(content_type: Option<&str>) -> bool {
+ content_type.is_some_and(|value| value.starts_with(JSON_MIME_TYPE))
+}
+
+/// The response body as the event stream rmcp consumes.
+fn event_stream(body: ProxyBody) -> BoxStream<'static, Result<Sse, SseError>> {
+ // `sse_stream` wants a stream whose error is a sized `Error`; the proxy's
+ // body error is boxed, so it goes through `io::Error`.
+ let bytes = body
+ .into_data_stream()
+ .map(|chunk| chunk.map_err(std::io::Error::other));
+ SseStream::from_byte_stream(bytes).boxed()
+}
+
+async fn read_body(body: ProxyBody) -> Result<Bytes, CallError> {
+ body.collect()
+ .await
+ .map(|collected| collected.to_bytes())
+ .map_err(|error| StreamableHttpError::Client(EgressCallError::Body(error.to_string())))
+}
+
+impl<Egress> StreamableHttpClient for EgressMcpClient<Egress>
+where
+ Egress: EgressService + 'static,
+{
+ type Error = EgressCallError;
+
+ async fn post_message(
+ &self,
+ uri: Arc<str>,
+ message: ClientJsonRpcMessage,
+ session_id: Option<Arc<str>>,
+ auth_header: Option<String>,
+ custom_headers: HashMap<HeaderName, HeaderValue>,
+ ) -> Result<StreamableHttpPostResponse, CallError> {
+ let Addressed { token, target } = address(&uri, auth_header)?;
+ let body = serde_json::to_vec(&message)?;
+ let mut request = build_request(
+ Method::POST,
+ &uri,
+ session_id.as_deref(),
+ custom_headers,
+ full_body(body),
+ )?;
+ request
+ .headers_mut()
+ .insert(CONTENT_TYPE, HeaderValue::from_static(JSON_MIME_TYPE));
+
+ let response = self
+ .egress
+ .proxy(&token, target, request)
+ .await
+ .map_err(|error| StreamableHttpError::Client(EgressCallError::Egress(error)))?;
+
+ let status = response.status();
+ if matches!(status, StatusCode::ACCEPTED | StatusCode::NO_CONTENT) {
+ return Ok(StreamableHttpPostResponse::Accepted);
+ }
+ if status == StatusCode::NOT_FOUND && session_id.is_some() {
+ return Err(StreamableHttpError::SessionExpired);
+ }
+ let content_type = content_type(&response);
+ let response_session = self::session_id(&response);
+ if !status.is_success() {
+ // A JSON-RPC error in the body is the server speaking and goes
+ // to the model; anything else is transport failure.
+ let body = read_body(response.into_body()).await?;
+ if is_json(content_type.as_deref())
+ && let Ok(message @ JsonRpcMessage::Error(_)) =
+ serde_json::from_slice::<ServerJsonRpcMessage>(&body)
+ {
+ return Ok(StreamableHttpPostResponse::Json(message, response_session));
+ }
+ return Err(StreamableHttpError::UnexpectedServerResponse(
+ format!("HTTP {status}: {}", String::from_utf8_lossy(&body)).into(),
+ ));
+ }
+ if is_event_stream(content_type.as_deref()) {
+ return Ok(StreamableHttpPostResponse::Sse(
+ event_stream(response.into_body()),
+ response_session,
+ ));
+ }
+ if is_json(content_type.as_deref()) {
+ let body = read_body(response.into_body()).await?;
+ return match serde_json::from_slice::<ServerJsonRpcMessage>(&body) {
+ Ok(message) => Ok(StreamableHttpPostResponse::Json(message, response_session)),
+ Err(error) => {
+ // A 200 to a notification with no `id` is not a message;
+ // rmcp's own client treats it as accepted, so do the same.
+ tracing::warn!(error = ?error, "MCP response was not a JSON-RPC message; treating it as accepted");
+ Ok(StreamableHttpPostResponse::Accepted)
+ }
+ };
+ }
+ Err(StreamableHttpError::UnexpectedContentType(content_type))
+ }
+
+ async fn delete_session(
+ &self,
+ uri: Arc<str>,
+ session_id: Arc<str>,
+ auth_header: Option<String>,
+ custom_headers: HashMap<HeaderName, HeaderValue>,
+ ) -> Result<(), CallError> {
+ let Addressed { token, target } = address(&uri, auth_header)?;
+ let request = build_request(
+ Method::DELETE,
+ &uri,
+ Some(&session_id),
+ custom_headers,
+ empty_body(),
+ )?;
+ let response = self
+ .egress
+ .proxy(&token, target, request)
+ .await
+ .map_err(|error| StreamableHttpError::Client(EgressCallError::Egress(error)))?;
+ let status = response.status();
+ if status == StatusCode::METHOD_NOT_ALLOWED {
+ tracing::debug!("the MCP server does not support deleting a session");
+ return Ok(());
+ }
+ if !status.is_success() {
+ return Err(StreamableHttpError::UnexpectedServerResponse(
+ format!("HTTP {status} deleting the MCP session").into(),
+ ));
+ }
+ Ok(())
+ }
+
+ async fn get_stream(
+ &self,
+ uri: Arc<str>,
+ session_id: Arc<str>,
+ last_event_id: Option<String>,
+ auth_header: Option<String>,
+ custom_headers: HashMap<HeaderName, HeaderValue>,
+ ) -> Result<BoxStream<'static, Result<Sse, SseError>>, CallError> {
+ let Addressed { token, target } = address(&uri, auth_header)?;
+ let mut request = build_request(
+ Method::GET,
+ &uri,
+ Some(&session_id),
+ custom_headers,
+ empty_body(),
+ )?;
+ if let Some(last_event_id) = last_event_id {
+ let value = HeaderValue::from_str(&last_event_id).map_err(|_| {
+ StreamableHttpError::UnexpectedServerResponse("invalid last event id".into())
+ })?;
+ request
+ .headers_mut()
+ .insert(HeaderName::from_static(HEADER_LAST_EVENT_ID), value);
+ }
+ let response = self
+ .egress
+ .proxy(&token, target, request)
+ .await
+ .map_err(|error| StreamableHttpError::Client(EgressCallError::Egress(error)))?;
+ let status = response.status();
+ if status == StatusCode::METHOD_NOT_ALLOWED {
+ return Err(StreamableHttpError::ServerDoesNotSupportSse);
+ }
+ if !status.is_success() {
+ return Err(StreamableHttpError::UnexpectedServerResponse(
+ format!("HTTP {status} opening the MCP event stream").into(),
+ ));
+ }
+ let content_type = content_type(&response);
+ if !is_event_stream(content_type.as_deref()) && !is_json(content_type.as_deref()) {
+ return Err(StreamableHttpError::UnexpectedContentType(content_type));
+ }
+ Ok(event_stream(response.into_body()))
+ }
+}
diff --git a/crates/agent_inmem/src/outbound/egress_mcp/test.rs b/crates/agent_inmem/src/outbound/egress_mcp/test.rs
new file mode 100644
index 0000000000..ae57b93e7f
--- /dev/null
+++ b/crates/agent_inmem/src/outbound/egress_mcp/test.rs
@@ -0,0 +1,206 @@
+use std::sync::Mutex;
+
+use agent_egress::domain::model::McpServerSlug;
+use mcp_toolset::client_info;
+use rmcp::ServiceExt as _;
+use rmcp::transport::StreamableHttpClientTransport;
+use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
+use serde_json::{Value, json};
+
+use super::*;
+
+/// An egress service standing in for the proxy: it records who called for
+/// what and speaks just enough MCP to complete a handshake and list tools.
+#[derive(Default)]
+struct StubEgress {
+ seen: Mutex<Vec<(String, EgressTarget)>>,
+}
+
+impl StubEgress {
+ fn seen(&self) -> Vec<(String, EgressTarget)> {
+ self.seen.lock().expect("lock").clone()
+ }
+}
+
+fn json_response(status: StatusCode, body: Value) -> ProxyResponse {
+ let mut response = http::Response::new(full_body(body.to_string().into_bytes()));
+ *response.status_mut() = status;
+ response
+ .headers_mut()
+ .insert(CONTENT_TYPE, HeaderValue::from_static(JSON_MIME_TYPE));
+ response
+ .headers_mut()
+ .insert(HEADER_SESSION_ID, HeaderValue::from_static("stub-session"));
+ response
+}
+
+impl EgressService for StubEgress {
+ async fn proxy(
+ &self,
+ token: &SessionToken,
+ target: EgressTarget,
+ request: ProxyRequest,
+ ) -> Result<ProxyResponse, EgressError> {
+ self.seen
+ .lock()
+ .expect("lock")
+ .push((token.as_str().to_owned(), target));
+
+ if *request.method() != Method::POST {
+ let mut response = http::Response::new(empty_body());
+ *response.status_mut() = StatusCode::METHOD_NOT_ALLOWED;
+ return Ok(response);
+ }
+ let body = request
+ .into_body()
+ .collect()
+ .await
+ .expect("body")
+ .to_bytes();
+ let call: Value = serde_json::from_slice(&body).expect("json-rpc");
+ let id = call.get("id").cloned();
+ let result = match call["method"].as_str() {
+ Some("initialize") => json!({
+ "protocolVersion": "2025-03-26",
+ "capabilities": {"tools": {}},
+ "serverInfo": {"name": "stub", "version": "0"},
+ }),
+ Some("tools/list") => json!({
+ "tools": [{
+ "name": "echo",
+ "description": "Echoes",
+ "inputSchema": {"type": "object"},
+ }],
+ }),
+ // Notifications carry no id and are acknowledged with nothing.
+ _ if id.is_none() => {
+ let mut response = http::Response::new(empty_body());
+ *response.status_mut() = StatusCode::ACCEPTED;
+ return Ok(response);
+ }
+ _ => {
+ return Ok(json_response(
+ StatusCode::NOT_FOUND,
+ json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601, "message": "no such method"}}),
+ ));
+ }
+ };
+ Ok(json_response(
+ StatusCode::OK,
+ json!({"jsonrpc": "2.0", "id": id, "result": result}),
+ ))
+ }
+}
+
+fn hubspot() -> EgressTarget {
+ EgressTarget::McpServer(McpDestination::Connected(
+ McpServerSlug::parse("hubspot").expect("slug"),
+ ))
+}
+
+#[tokio::test]
+async fn a_handshake_and_tool_listing_go_through_the_service_as_the_session() {
+ let egress = Arc::new(StubEgress::default());
+ let client = EgressMcpClient::new(Arc::clone(&egress));
+ let config =
+ StreamableHttpClientTransportConfig::with_uri("http://egress.internal/mcp/hubspot")
+ .auth_header("session-token");
+ let transport = StreamableHttpClientTransport::with_client(client, config);
+
+ let server = client_info().serve(transport).await.expect("handshake");
+ let tools = server.list_all_tools().await.expect("tools/list");
+ assert_eq!(
+ tools
+ .iter()
+ .map(|tool| tool.name.as_ref())
+ .collect::<Vec<_>>(),
+ ["echo"]
+ );
+ server.cancel().await.expect("close");
+
+ let seen = egress.seen();
+ assert!(
+ seen.len() >= 3,
+ "initialize, initialized, tools/list: {seen:?}"
+ );
+ for (token, target) in &seen {
+ assert_eq!(token, "session-token");
+ assert_eq!(*target, hubspot());
+ }
+}
+
+#[tokio::test]
+async fn a_url_off_the_proxy_routes_is_refused_before_the_service_is_called() {
+ let egress = Arc::new(StubEgress::default());
+ let client = EgressMcpClient::new(Arc::clone(&egress));
+
+ let error = client
+ .post_message(
+ Arc::from("http://egress.internal/git/info/refs"),
+ ClientJsonRpcMessage::notification(
+ rmcp::model::ClientNotification::InitializedNotification(Default::default()),
+ ),
+ None,
+ Some("session-token".to_owned()),
+ HashMap::new(),
+ )
+ .await
+ .expect_err("not an MCP route");
+ assert!(
+ matches!(
+ error,
+ StreamableHttpError::Client(EgressCallError::NotAnEgressUrl(_))
+ ),
+ "{error:?}"
+ );
+ assert!(egress.seen().is_empty());
+}
+
+#[tokio::test]
+async fn a_server_entry_without_a_token_is_refused_before_the_service_is_called() {
+ let egress = Arc::new(StubEgress::default());
+ let client = EgressMcpClient::new(Arc::clone(&egress));
+
+ let error = client
+ .delete_session(
+ Arc::from("http://egress.internal/mcp/hubspot"),
+ Arc::from("stub-session"),
+ None,
+ HashMap::new(),
+ )
+ .await
+ .expect_err("no token");
+ assert!(
+ matches!(
+ error,
+ StreamableHttpError::Client(EgressCallError::NoSessionToken)
+ ),
+ "{error:?}"
+ );
+ assert!(egress.seen().is_empty());
+}
+
+#[tokio::test]
+async fn the_macro_route_names_macros_own_server() {
+ let egress = Arc::new(StubEgress::default());
+ let client = EgressMcpClient::new(Arc::clone(&egress));
+
+ // The stub answers DELETE with 405, which the client reads as "nothing to
+ // delete", so this exercises the address step alone.
+ client
+ .delete_session(
+ Arc::from("http://egress.internal/mcp-macro"),
+ Arc::from("stub-session"),
+ Some("session-token".to_owned()),
+ HashMap::new(),
+ )
+ .await
+ .expect("405 is fine");
+ assert_eq!(
+ egress.seen(),
+ vec![(
+ "session-token".to_owned(),
+ EgressTarget::McpServer(McpDestination::Macro)
+ )]
+ );
+}
diff --git a/crates/agent_inmem/src/outbound/manager.rs b/crates/agent_inmem/src/outbound/manager.rs
index 42e44bb031..29251e9335 100644
--- a/crates/agent_inmem/src/outbound/manager.rs
+++ b/crates/agent_inmem/src/outbound/manager.rs
@@ -17,6 +17,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use crate::domain::agent::{AgentState, serve};
use crate::domain::engine::TurnEngine;
+use crate::domain::mcp::DynMcpToolConnector;
use crate::domain::replay::{FrameSource, replay_history};
use crate::domain::session::{SessionState, SessionStore};
@@ -62,33 +63,64 @@ impl Drop for LiveAgent {
pub struct InMemAgentManager {
engine: Arc<dyn TurnEngine>,
frames: Arc<dyn FrameSource>,
+ mcp: Arc<dyn DynMcpToolConnector>,
store: Arc<SessionStore>,
live: DashMap<AgentSessionId, LiveAgent>,
+ /// Each live session's egress token. An in-process session has no
+ /// container environment to read it back from, so the manager is the
+ /// one place it survives spawn; a resume after a restart finds nothing
+ /// here and advertises no servers, exactly like a sandbox whose
+ /// container is gone.
+ tokens: DashMap<AgentSessionId, String>,
}
impl InMemAgentManager {
/// A manager running every session's turns through `engine`, rebuilding
- /// cold sessions' conversations from `frames`.
+ /// cold sessions' conversations from `frames`, and dialing the MCP
+ /// servers each session is handed through `mcp`.
#[must_use]
- pub fn new(engine: Arc<dyn TurnEngine>, frames: Arc<dyn FrameSource>) -> Self {
+ pub fn new(
+ engine: Arc<dyn TurnEngine>,
+ frames: Arc<dyn FrameSource>,
+ mcp: Arc<dyn DynMcpToolConnector>,
+ ) -> Self {
Self {
engine,
frames,
+ mcp,
store: Arc::new(SessionStore::new()),
live: DashMap::new(),
+ tokens: DashMap::new(),
}
}
+ /// The egress token `attach` was handed for `session`, if this process
+ /// still holds it.
+ #[must_use]
+ pub fn session_token(&self, session: AgentSessionId) -> Option<String> {
+ self.tokens.get(&session).map(|token| token.clone())
+ }
+
/// Start (or restart) the session's agent and return the transport the
/// harness attaches. Spawn and resume are the same operation here: the
/// conversation store is what persists across reattachment, not the
/// task - and a session this process has never held (a fresh spawn, or a
/// resume after a restart) gets its conversation rebuilt from the durable
/// frame log first.
+ ///
+ /// `session_token` is the egress token minted at spawn; a resume passes
+ /// `None` and keeps whatever spawn stored.
#[must_use]
- pub async fn attach(&self, facts: SessionFacts) -> ServerChannel {
+ pub async fn attach(
+ &self,
+ facts: SessionFacts,
+ session_token: Option<String>,
+ ) -> ServerChannel {
// A replaced agent must die before its successor serves the session.
self.live.remove(&facts.id);
+ if let Some(token) = session_token {
+ self.tokens.insert(facts.id, token);
+ }
if !self.store.contains_key(&facts.id) {
// Loaded before taking the entry so the read never blocks the
// map; `or_insert_with` still wins any race to create it.
@@ -110,6 +142,8 @@ impl InMemAgentManager {
store: Arc::clone(&self.store),
active_cancel: std::sync::Mutex::new(Vec::new()),
turn_lock: tokio::sync::Mutex::new(()),
+ mcp: Arc::clone(&self.mcp),
+ mcp_tools: std::sync::Mutex::new(None),
});
let session_id = facts.id;
let task = tokio::spawn(async move {
@@ -137,5 +171,6 @@ impl InMemAgentManager {
pub fn teardown(&self, session: AgentSessionId) {
self.live.remove(&session);
self.store.remove(&session);
+ self.tokens.remove(&session);
}
}
diff --git a/crates/agent_inmem/src/outbound/manager/test.rs b/crates/agent_inmem/src/outbound/manager/test.rs
index 09857ae2ab..a412759b1e 100644
--- a/crates/agent_inmem/src/outbound/manager/test.rs
+++ b/crates/agent_inmem/src/outbound/manager/test.rs
@@ -40,7 +40,7 @@ async fn attach_retrying(
) {
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
loop {
- let transport = manager.attach(facts.clone()).await;
+ let transport = manager.attach(facts.clone(), None).await;
match sessions
.attach_session(id, RuntimeAttachment::solo(transport))
.await
@@ -86,7 +86,11 @@ fn owner() -> MacroUserIdStr<'static> {
}
fn manager(repo: &InMemoryAgentSessionRepo, engine: Arc<ScriptedEngine>) -> InMemAgentManager {
- InMemAgentManager::new(engine, Arc::new(LogFrameSource::new(repo.clone())))
+ InMemAgentManager::new(
+ engine,
+ Arc::new(LogFrameSource::new(repo.clone())),
+ Arc::new(crate::domain::mcp::NoMcpServers),
+ )
}
fn facts(id: AgentSessionId) -> SessionFacts {
@@ -154,6 +158,7 @@ async fn a_prompt_runs_end_to_end_through_the_real_session_machine() {
workspace: "/workspace".to_owned(),
sandbox_size: agent_session::domain::model::SandboxSize::Default,
instructions: None,
+ mcp_servers: Default::default(),
egress_token_hash: None,
})
.await
@@ -165,7 +170,7 @@ async fn a_prompt_runs_end_to_end_through_the_real_session_machine() {
"streamed reply".to_owned(),
)])),
);
- let transport = manager.attach(facts(id)).await;
+ let transport = manager.attach(facts(id), None).await;
sessions
.attach_session(id, RuntimeAttachment::solo(transport))
.await
@@ -222,7 +227,7 @@ async fn a_prompt_runs_end_to_end_through_the_real_session_machine() {
// disconnect-then-resume order the harness's deliver path drives.
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
loop {
- let transport = manager.attach(facts(id)).await;
+ let transport = manager.attach(facts(id), None).await;
match sessions
.attach_session(id, RuntimeAttachment::solo(transport))
.await
@@ -288,6 +293,7 @@ async fn a_restarted_manager_rebuilds_the_conversation_from_the_log() {
workspace: "/workspace".to_owned(),
sandbox_size: agent_session::domain::model::SandboxSize::Default,
instructions: None,
+ mcp_servers: Default::default(),
egress_token_hash: None,
})
.await
@@ -299,7 +305,7 @@ async fn a_restarted_manager_rebuilds_the_conversation_from_the_log() {
"streamed reply".to_owned(),
)])),
);
- let transport = before.attach(facts(id)).await;
+ let transport = before.attach(facts(id), None).await;
sessions
.attach_session(id, RuntimeAttachment::solo(transport))
.await
@@ -341,10 +347,13 @@ async fn a_restarted_manager_rebuilds_the_conversation_from_the_log() {
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
loop {
let transport = after
- .attach(SessionFacts {
- acp_session_id: row.acp_session_id.clone(),
- ..facts(id)
- })
+ .attach(
+ SessionFacts {
+ acp_session_id: row.acp_session_id.clone(),
+ ..facts(id)
+ },
+ None,
+ )
.await;
match sessions
.attach_session(id, RuntimeAttachment::solo(transport))
@@ -426,6 +435,7 @@ async fn instructions_reach_every_turn_including_after_a_reattach() {
workspace: "/workspace".to_owned(),
sandbox_size: agent_session::domain::model::SandboxSize::Default,
instructions: Some(INSTRUCTIONS.to_owned()),
+ mcp_servers: Default::default(),
egress_token_hash: None,
})
.await
@@ -495,6 +505,7 @@ async fn a_session_without_instructions_hands_the_engine_none() {
workspace: "/workspace".to_owned(),
sandbox_size: agent_session::domain::model::SandboxSize::Default,
instructions: None,
+ mcp_servers: Default::default(),
egress_token_hash: None,
})
.await
@@ -504,7 +515,7 @@ async fn a_session_without_instructions_hands_the_engine_none() {
"acknowledged".to_owned(),
)]));
let manager = manager(&repo, Arc::clone(&engine));
- let transport = manager.attach(facts(id)).await;
+ let transport = manager.attach(facts(id), None).await;
sessions
.attach_session(id, RuntimeAttachment::solo(transport))
.await
@@ -522,3 +533,25 @@ async fn a_session_without_instructions_hands_the_engine_none() {
assert_eq!(engine.requests()[0].instructions, None);
}
+
+/// The egress token has no container environment to live in here, so the
+/// manager keeps what spawn handed it: a resume finds it, teardown forgets it.
+#[tokio::test]
+async fn the_manager_remembers_the_egress_token_from_spawn_until_teardown() {
+ let repo = InMemoryAgentSessionRepo::new();
+ let manager = manager(&repo, Arc::new(ScriptedEngine::new(Vec::new())));
+ let id = AgentSessionId::new();
+ assert_eq!(manager.session_token(id), None);
+
+ let _spawned = manager
+ .attach(facts(id), Some("session-token".to_owned()))
+ .await;
+ assert_eq!(manager.session_token(id).as_deref(), Some("session-token"));
+
+ // A resume passes nothing and keeps what spawn stored.
+ let _resumed = manager.attach(facts(id), None).await;
+ assert_eq!(manager.session_token(id).as_deref(), Some("session-token"));
+
+ manager.teardown(id);
+ assert_eq!(manager.session_token(id), None);
+}
diff --git a/crates/agent_inmem/src/outbound/mod.rs b/crates/agent_inmem/src/outbound/mod.rs
index 92522caee0..30039024bf 100644
--- a/crates/agent_inmem/src/outbound/mod.rs
+++ b/crates/agent_inmem/src/outbound/mod.rs
@@ -1,6 +1,8 @@
//! Outbound adapters: the production turn engine and the per-session agent
//! manager.
+pub mod acp_mcp;
+pub mod egress_mcp;
pub mod log_frames;
pub mod manager;
pub mod rig_engine;
diff --git a/crates/agent_inmem/src/outbound/rig_engine.rs b/crates/agent_inmem/src/outbound/rig_engine.rs
index 084d038bf4..e70d504add 100644
--- a/crates/agent_inmem/src/outbound/rig_engine.rs
+++ b/crates/agent_inmem/src/outbound/rig_engine.rs
@@ -75,6 +75,7 @@ async fn drive_turn(
model,
instructions,
messages,
+ mcp_tools,
cancel,
} = request;
@@ -86,7 +87,13 @@ async fn drive_turn(
user_memory.as_deref(),
);
- let toolset: Arc<dyn AiToolSet<_> + Send + Sync> = tools.toolset;
+ // The MCP servers the session was handed sit next to the native tools
+ // the way they do in chat: static tools on every request, MCP tools in
+ // the searchable catalog behind `SearchTools`.
+ let toolset: Arc<dyn AiToolSet<_> + Send + Sync> = match mcp_tools {
+ Some(mcp) => Arc::new(mcp_select::CombinedToolSet::new(tools.toolset, mcp)),
+ None => tools.toolset,
+ };
let agent_loop = AgentLoop::new(base_context.recorder.clone()).with_model(&model);
let usage_ctx = ai_usage::UsageContext::new(ai_usage::AiFeature::AgentSession, owner);
// Carry the feature on the context so tool-spawned subagents attribute to it.
diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.toml
index e121d87f8f..20943de5f6 100644
--- a/crates/agent_session/Cargo.toml
+++ b/crates/agent_session/Cargo.toml
@@ -36,7 +36,7 @@ macro_service_urls = { path = "../macro_service_urls" }
macro_user_id = { path = "../macro_user_id", features = ["sqlx"] }
utoipa = { workspace = true }
rootcause = { workspace = true }
-sqlx = { workspace = true }
+sqlx = { workspace = true, features = ["json"] }
chrono = { workspace = true }
thiserror = { workspace = true }
anyhow = { workspace = true }
diff --git a/crates/agent_session/src/bin/seed_jsonl.rs b/crates/agent_session/src/bin/seed_jsonl.rs
index 315618f1a9..c70d689a1c 100644
--- a/crates/agent_session/src/bin/seed_jsonl.rs
+++ b/crates/agent_session/src/bin/seed_jsonl.rs
@@ -251,6 +251,7 @@ async fn seed(args: &Args) -> Result<(), SeedError> {
sandbox_size: agent_session::domain::model::SandboxSize::Default,
// A recording is replayed, not run; nothing reads instructions.
instructions: None,
+ mcp_servers: Default::default(),
egress_token_hash: None,
},
)
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rs
index aa9624855e..ba92a32f66 100644
--- a/crates/agent_session/src/domain/model.rs
+++ b/crates/agent_session/src/domain/model.rs
@@ -150,6 +150,13 @@ pub enum SessionStatus {
Disconnected,
}
+/// Which Pipedream MCP servers a session is handed: the agent's own choice,
+/// snapshotted onto the session at creation like `instructions`. The ACP
+/// agent is given its server list once per attach and cannot refresh it, so
+/// the snapshot is what every later attach re-advertises; editing the agent
+/// applies to its next session.
+pub use bots::domain::models::{AgentMcpServer, AgentMcpServers};
+
/// Caller-provided values required to create an agent session.
#[derive(Debug, Clone)]
pub struct CreateAgentSessionParams {
@@ -180,6 +187,8 @@ pub struct CreateAgentSessionParams {
/// provider, but every provider needs the same answer for the session's
/// whole life.
pub instructions: Option<String>,
+ /// Which MCP servers the session is handed; see [`AgentMcpServers`].
+ pub mcp_servers: AgentMcpServers,
/// SHA-256 hex of the opaque token the session's sandbox presents to the
/// egress proxy, or `None` for a session that never gets one.
///
@@ -226,6 +235,8 @@ pub struct AgentSession {
/// creation. Immutable for the session's life; `None` when none were
/// stated.
pub instructions: Option<String>,
+ /// Which MCP servers the session is handed, snapshotted at creation.
+ pub mcp_servers: AgentMcpServers,
/// ACP session if we have one
pub acp_session_id: Option<SessionId>,
/// The provider-side identity, when an external provider serves this
diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rs
index 14f46e159e..065de6837c 100644
--- a/crates/agent_session/src/inbound/axum_router/test.rs
+++ b/crates/agent_session/src/inbound/axum_router/test.rs
@@ -120,6 +120,7 @@ impl SessionOpener for RecordingOpener {
workspace: request.workspace.clone(),
sandbox_size: crate::domain::model::SandboxSize::Default,
instructions: request.instructions.clone(),
+ mcp_servers: Default::default(),
acp_session_id: None,
external: None,
status: SessionStatus::NoMessages,
@@ -148,6 +149,7 @@ impl SessionOpener for RecordingOpener {
workspace: crate::MANAGED_CONTAINER_WORKSPACE.to_owned(),
sandbox_size: crate::domain::model::SandboxSize::Default,
instructions: request.instructions.clone(),
+ mcp_servers: Default::default(),
acp_session_id: None,
external: None,
status: SessionStatus::NoMessages,
diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rs
index ab02baf791..81fe35074c 100644
--- a/crates/agent_session/src/outbound/postgres.rs
+++ b/crates/agent_session/src/outbound/postgres.rs
@@ -7,7 +7,7 @@ mod test;
use crate::domain::error::{AgentSessionError, Result};
use crate::domain::model::{
- AgentSession, AgentSessionId, AgentSessionLog, ChannelSession, ClaimOutcome,
+ AgentMcpServers, AgentSession, AgentSessionId, AgentSessionLog, ChannelSession, ClaimOutcome,
CreateAgentSessionParams, ExternalSession, ManagerFence, Message, ReplicaAddress, ReplicaId,
SandboxSize, SessionBot, SessionClaim, SessionManager, SessionStatus, StoredAgentSessionLog,
};
@@ -111,6 +111,8 @@ struct AgentSessionRow {
workspace: String,
sandbox_size: String,
instructions: Option<String>,
+ mcp_scope: String,
+ mcp_servers: serde_json::Value,
acp_session_id: Option<String>,
external_provider: Option<String>,
external_id: Option<String>,
@@ -142,6 +144,11 @@ impl TryFrom<AgentSessionRow> for AgentSession {
workspace: row.workspace,
sandbox_size: parse_sandbox_size(&row.sandbox_size)?,
instructions: row.instructions,
+ mcp_servers: AgentMcpServers::from_columns(
+ &row.mcp_scope,
+ serde_json::from_value(row.mcp_servers)
+ .context("agent session has unparseable mcp servers")?,
+ )?,
acp_session_id: row.acp_session_id.map(Into::into),
external: row
.external_provider
@@ -173,8 +180,11 @@ impl AgentSessionRepo for PgAgentSessionRepo {
workspace,
sandbox_size,
instructions,
+ mcp_servers,
egress_token_hash,
} = params;
+ let mcp_servers_json = serde_json::to_value(mcp_servers.servers())
+ .context("serialize agent session mcp servers")?;
// The session row and its access grants land together: a crash between
// the two would leave a session nobody - not even its owner -
@@ -192,13 +202,14 @@ impl AgentSessionRepo for PgAgentSessionRepo {
INSERT INTO agent_session (
id, owner_id, thread_id, originating_message_id, bot_id, model,
harness, repo_url, workspace, sandbox_size, instructions,
- acp_session_id, status, status_event_name, egress_token_hash
+ acp_session_id, status, status_event_name, egress_token_hash,
+ mcp_scope, mcp_servers
)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)
RETURNING
id, name, owner_id, thread_id, originating_message_id, bot_id,
model, harness, repo_url, workspace, sandbox_size, instructions,
- acp_session_id, status,
+ mcp_scope, mcp_servers, acp_session_id, status,
status_event_name, created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?",
@@ -221,6 +232,8 @@ impl AgentSessionRepo for PgAgentSessionRepo {
status,
status_event_name,
egress_token_hash,
+ mcp_servers.scope_str(),
+ mcp_servers_json,
)
.fetch_one(&mut *transaction)
.await
@@ -289,7 +302,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {
SELECT
id, name, owner_id, thread_id, originating_message_id, bot_id,
model, harness, repo_url, workspace, sandbox_size, instructions,
- acp_session_id, status,
+ mcp_scope, mcp_servers, acp_session_id, status,
status_event_name, agent_session.created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?",
@@ -322,7 +335,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {
SELECT
id, name, owner_id, thread_id, originating_message_id, bot_id,
model, harness, repo_url, workspace, sandbox_size, instructions,
- acp_session_id, status,
+ mcp_scope, mcp_servers, acp_session_id, status,
status_event_name, agent_session.created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?",
@@ -361,7 +374,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {
SELECT
id, name, owner_id, thread_id, originating_message_id, bot_id,
model, harness, repo_url, workspace, sandbox_size, instructions,
- acp_session_id, status,
+ mcp_scope, mcp_servers, acp_session_id, status,
status_event_name, agent_session.created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?",
@@ -393,7 +406,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {
SELECT
id, name, owner_id, thread_id, originating_message_id, bot_id,
model, harness, repo_url, workspace, sandbox_size, instructions,
- acp_session_id, status,
+ mcp_scope, mcp_servers, acp_session_id, status,
status_event_name, agent_session.created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?",
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index 1d20c178c7..db1342d81d 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -1,5 +1,5 @@
use super::*;
-use crate::domain::model::DEFAULT_AGENT_SESSION_NAME;
+use crate::domain::model::{AgentMcpServer, DEFAULT_AGENT_SESSION_NAME};
use crate::domain::ports::AgentSessionRepo;
use agent_client_protocol::RawJsonRpcMessage;
use agent_runtime_protocol::domain::schema::v0::{AcpMessage, SystemEvent};
@@ -94,6 +94,7 @@ fn new_session(
workspace: "/workspace".to_string(),
sandbox_size: SandboxSize::Default,
instructions: None,
+ mcp_servers: AgentMcpServers::OwnerConnections,
egress_token_hash: None,
}
}
@@ -244,6 +245,54 @@ async fn instructions_round_trip_on_every_read_path(pool: PgPool) {
);
}
+/// The MCP selection is a snapshot like `instructions`: whatever was chosen at
+/// creation comes back identically on every read path, servers and names
+/// included, and the default is the owner's connections.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn mcp_server_selection_round_trips_on_every_read_path(pool: PgPool) {
+ let repo = PgAgentSessionRepo::new(pool.clone());
+ let bot_id = create_test_bot(&pool).await;
+ let (_channel_id, thread_id, originating_message_id) =
+ insert_originating_thread_fixture(&pool).await;
+ let selection = AgentMcpServers::Selected {
+ servers: vec![
+ AgentMcpServer {
+ app_slug: "linear".to_owned(),
+ server_name: "Linear".to_owned(),
+ },
+ AgentMcpServer {
+ app_slug: "notion".to_owned(),
+ server_name: "Notion".to_owned(),
+ },
+ ],
+ };
+ let params = CreateAgentSessionParams {
+ mcp_servers: selection.clone(),
+ egress_token_hash: Some("mcp-token-hash".to_owned()),
+ ..new_session(bot_id, Some(thread_id), Some(originating_message_id))
+ };
+ let id = params.id;
+
+ let created = create_session(&repo, params).await;
+ assert_eq!(created.mcp_servers, selection);
+ let fetched = AgentSessionRepo::get(&repo, id)
+ .await
+ .expect("get agent session");
+ assert_eq!(fetched.mcp_servers, selection);
+ let by_token = AgentSessionRepo::find_by_egress_token_hash(&repo, "mcp-token-hash")
+ .await
+ .expect("the token lookup should run")
+ .expect("the token should resolve to the session");
+ assert_eq!(by_token.mcp_servers, selection);
+
+ let default = create_session(&repo, new_session(bot_id, None, None)).await;
+ assert_eq!(default.mcp_servers, AgentMcpServers::OwnerConnections);
+ let fetched = AgentSessionRepo::get(&repo, default.id)
+ .await
+ .expect("get agent session");
+ assert_eq!(fetched.mcp_servers, AgentMcpServers::OwnerConnections);
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn set_acp_session_id_updates_only_the_resume_identity(pool: PgPool) {
let repo = PgAgentSessionRepo::new(pool.clone());
diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rs
index 578476df99..a48822588b 100644
--- a/crates/agent_session/src/testing.rs
+++ b/crates/agent_session/src/testing.rs
@@ -6,7 +6,7 @@
use crate::domain::error::{AgentSessionError, Result};
use crate::domain::model::{
- AgentSession, AgentSessionId, AgentSessionLog, ChannelSession, ClaimOutcome,
+ AgentMcpServers, AgentSession, AgentSessionId, AgentSessionLog, ChannelSession, ClaimOutcome,
CreateAgentSessionParams, DEFAULT_AGENT_SESSION_NAME, LogAppended, ManagerFence,
ReplicaAddress, ReplicaId, SandboxSize, SessionBot, SessionClaim, SessionManager,
SessionStatus, StoredAgentSessionLog,
@@ -135,6 +135,7 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
workspace: params.workspace,
sandbox_size: params.sandbox_size,
instructions: params.instructions,
+ mcp_servers: params.mcp_servers,
acp_session_id: None,
external: None,
status: SessionStatus::default(),
@@ -549,6 +550,7 @@ pub fn test_agent_session(id: AgentSessionId) -> AgentSession {
workspace: "/workspace".to_string(),
sandbox_size: SandboxSize::Default,
instructions: None,
+ mcp_servers: AgentMcpServers::OwnerConnections,
acp_session_id: None,
external: None,
status: SessionStatus::NoMessages,
diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rs
index c04409a878..b984759b59 100644
--- a/crates/agent_trigger/src/domain/service/test.rs
+++ b/crates/agent_trigger/src/domain/service/test.rs
@@ -3,7 +3,7 @@ use super::*;
use agent_session::domain::error::AgentSessionError;
use agent_session::domain::model::{AgentSession, AgentSessionId, ChannelSession, SessionStatus};
use agent_session::domain::ports::MockAgentSessionRepo;
-use bots::domain::models::{Agent, AgentChannelScope, Bot, BotKind, BotOwner};
+use bots::domain::models::{Agent, AgentChannelScope, AgentMcpServers, Bot, BotKind, BotOwner};
use channel_sender::ChannelSender;
use channels::domain::models::{ChannelType, SimpleMention};
use chrono::Utc;
@@ -65,6 +65,7 @@ fn agent_with(bot_id: BotId, owner: BotOwner, channel_scope: AgentChannelScope)
default_model: "model".to_owned(),
channel_scope,
channel_ids: vec![],
+ mcp: AgentMcpServers::OwnerConnections,
}
}
@@ -115,6 +116,7 @@ fn session(id: AgentSessionId, bot_id: BotId) -> AgentSession {
workspace: "/workspace".to_owned(),
sandbox_size: agent_session::domain::model::SandboxSize::Default,
instructions: None,
+ mcp_servers: Default::default(),
acp_session_id: None,
external: None,
status: SessionStatus::NoMessages,
diff --git a/crates/bots/src/domain/models.rs b/crates/bots/src/domain/models.rs
index d84f8f85a8..c9ed3d094d 100644
--- a/crates/bots/src/domain/models.rs
+++ b/crates/bots/src/domain/models.rs
@@ -206,6 +206,65 @@ impl AgentChannelScope {
}
}
+/// Which Pipedream MCP servers an agent's sessions are handed.
+///
+/// One value for the whole choice, so a selection can never travel without
+/// its scope or a scope without its selection. Serialized with a `scope` tag,
+/// which the generated TypeScript sees as a discriminated union.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+#[serde(tag = "scope", rename_all = "snake_case")]
+pub enum AgentMcpServers {
+ /// Whatever apps the person running the session has connected.
+ #[default]
+ OwnerConnections,
+ /// Exactly these apps, connected or not.
+ Selected {
+ /// The apps, in the order the agent's author picked them.
+ servers: Vec<AgentMcpServer>,
+ },
+}
+
+impl AgentMcpServers {
+ /// Storage representation of the scope.
+ pub fn scope_str(&self) -> &'static str {
+ match self {
+ Self::OwnerConnections => "owner_connections",
+ Self::Selected { .. } => "selected",
+ }
+ }
+
+ /// The selected servers, empty under [`Self::OwnerConnections`].
+ pub fn servers(&self) -> &[AgentMcpServer] {
+ match self {
+ Self::OwnerConnections => &[],
+ Self::Selected { servers } => servers,
+ }
+ }
+
+ /// Rebuilds the value from its two stored columns.
+ pub fn from_columns(scope: &str, servers: Vec<AgentMcpServer>) -> anyhow::Result<Self> {
+ match scope {
+ "owner_connections" => Ok(Self::OwnerConnections),
+ "selected" => Ok(Self::Selected { servers }),
+ other => anyhow::bail!("unknown mcp scope {other:?}"),
+ }
+ }
+}
+
+/// One Pipedream app an agent lists under [`AgentMcpServers::Selected`].
+///
+/// Only the catalog identity is stored. Whether a given person has connected
+/// the app is theirs, resolved at call time by the egress proxy, never here.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct AgentMcpServer {
+ /// Pipedream app slug, e.g. `linear`.
+ pub app_slug: String,
+ /// Display name, e.g. `Linear`.
+ pub server_name: String,
+}
+
/// A persisted user- or team-owned AI agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
@@ -224,6 +283,8 @@ pub struct Agent {
pub channel_scope: AgentChannelScope,
/// Selected channel ids. Empty for a global agent.
pub channel_ids: Vec<Uuid>,
+ /// Which MCP servers sessions of this agent are handed.
+ pub mcp: AgentMcpServers,
}
/// Request to create a persisted AI agent.
@@ -255,6 +316,9 @@ pub struct CreateAgentRequest {
/// Selected channels. Must be non-empty only for `selected` scope.
#[serde(default)]
pub channel_ids: Vec<Uuid>,
+ /// Which MCP servers sessions of this agent are handed.
+ #[serde(default)]
+ pub mcp: AgentMcpServers,
}
/// Request to replace the editable configuration of a persisted AI agent.
@@ -286,6 +350,9 @@ pub struct UpdateAgentRequest {
/// Selected channels. Must be non-empty only for `selected` scope.
#[serde(default)]
pub channel_ids: Vec<Uuid>,
+ /// Which MCP servers sessions of this agent are handed.
+ #[serde(default)]
+ pub mcp: AgentMcpServers,
}
/// Channel containing a bot.
diff --git a/crates/bots/src/domain/service.rs b/crates/bots/src/domain/service.rs
index fbaf053176..205cefabd2 100644
--- a/crates/bots/src/domain/service.rs
+++ b/crates/bots/src/domain/service.rs
@@ -3,10 +3,11 @@
use super::{
events::{BotCreatedMetadata, BotDeletedMetadata, BotMacroEvent, BotUpdatedMetadata},
models::{
- Agent, AgentChannelScope, AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotId,
- BotKind, BotOwner, BotToken, BotTokenCandidate, CreateAgentRequest, CreateBotRequest,
- CreateBotTokenRequest, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse,
- HarnessId, HarnessOwner, PatchBotRequest, UpdateAgentRequest,
+ Agent, AgentChannelScope, AgentMcpServers, AuthenticatedBot, Bot, BotChannel,
+ BotChannelListCaller, BotId, BotKind, BotOwner, BotToken, BotTokenCandidate,
+ CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest,
+ CreateChannelScopedBotResponse, HarnessId, HarnessOwner, PatchBotRequest,
+ UpdateAgentRequest,
},
ports::{BotError, BotRepo, BotService},
tokens,
@@ -32,6 +33,42 @@ impl<R, B> BotServiceImpl<R, B> {
}
}
+/// The charset a Pipedream app slug may use. Mirrors the egress proxy's
+/// `McpServerSlug::parse` (restated here because bots must not depend on
+/// agent_egress): a slug that fails this could never be dialed, so it is
+/// refused where it is written rather than dropped where it is advertised.
+fn is_app_slug(slug: &str) -> bool {
+ !slug.is_empty()
+ && slug
+ .chars()
+ .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-' || ch == '_')
+}
+
+fn validate_mcp_servers(mcp: &AgentMcpServers) -> Result<(), BotError> {
+ let mut seen = std::collections::HashSet::new();
+ for server in mcp.servers() {
+ if !is_app_slug(&server.app_slug) {
+ return Err(BotError::BadRequest(format!(
+ "MCP server slug {:?} must be lowercase ascii, digits, '-' or '_'",
+ server.app_slug
+ )));
+ }
+ if server.server_name.trim().is_empty() {
+ return Err(BotError::BadRequest(format!(
+ "MCP server {} must have a name",
+ server.app_slug
+ )));
+ }
+ if !seen.insert(server.app_slug.as_str()) {
+ return Err(BotError::BadRequest(format!(
+ "MCP server {} is listed more than once",
+ server.app_slug
+ )));
+ }
+ }
+ Ok(())
+}
+
fn validate_handle(handle: &str) -> Result<(), BotError> {
if handle.is_empty()
|| handle.len() > 64
@@ -56,6 +93,7 @@ struct AgentFields<'a> {
default_model: &'a str,
channel_scope: AgentChannelScope,
channel_ids: &'a [Uuid],
+ mcp: &'a AgentMcpServers,
}
impl<'a> From<&'a CreateAgentRequest> for AgentFields<'a> {
@@ -68,6 +106,7 @@ impl<'a> From<&'a CreateAgentRequest> for AgentFields<'a> {
default_model: &req.default_model,
channel_scope: req.channel_scope,
channel_ids: &req.channel_ids,
+ mcp: &req.mcp,
}
}
}
@@ -82,6 +121,7 @@ impl<'a> From<&'a UpdateAgentRequest> for AgentFields<'a> {
default_model: &req.default_model,
channel_scope: req.channel_scope,
channel_ids: &req.channel_ids,
+ mcp: &req.mcp,
}
}
}
@@ -95,8 +135,10 @@ fn validate_agent_fields(
default_model,
channel_scope,
channel_ids,
+ mcp,
}: AgentFields<'_>,
) -> Result<(), BotError> {
+ validate_mcp_servers(mcp)?;
validate_handle(handle)?;
if name.trim().is_empty() {
return Err(BotError::BadRequest(
diff --git a/crates/bots/src/outbound/pg_bots_repo.rs b/crates/bots/src/outbound/pg_bots_repo.rs
index da60fa2cc2..b8359ac3ac 100644
--- a/crates/bots/src/outbound/pg_bots_repo.rs
+++ b/crates/bots/src/outbound/pg_bots_repo.rs
@@ -5,10 +5,10 @@ mod tests;
use crate::domain::{
models::{
- Agent, AgentChannelScope, AuthenticatedBot, Bot, BotChannel, BotChannelType, BotId,
- BotKind, BotOwner, BotToken, BotTokenCandidate, CreateAgentRequest, CreateBotRequest,
- CreateBotTokenRequest, CreateChannelScopedBotRequest, HarnessId, HarnessOwner,
- PatchBotRequest, UpdateAgentRequest,
+ Agent, AgentChannelScope, AgentMcpServer, AgentMcpServers, AuthenticatedBot, Bot,
+ BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BotTokenCandidate,
+ CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest,
+ HarnessId, HarnessOwner, PatchBotRequest, UpdateAgentRequest,
},
ports::BotRepo,
};
@@ -112,6 +112,9 @@ struct AgentRow {
default_model: String,
channel_scope: String,
channel_ids: Vec<Uuid>,
+ mcp_scope: String,
+ mcp_app_slugs: Vec<String>,
+ mcp_server_names: Vec<String>,
}
impl TryFrom<AgentRow> for Agent {
@@ -122,6 +125,19 @@ impl TryFrom<AgentRow> for Agent {
.channel_scope
.parse::<AgentChannelScope>()
.map_err(anyhow::Error::msg)?;
+ if row.mcp_app_slugs.len() != row.mcp_server_names.len() {
+ anyhow::bail!("agent {} mcp server columns disagree in length", row.id);
+ }
+ let mcp_servers = row
+ .mcp_app_slugs
+ .into_iter()
+ .zip(row.mcp_server_names)
+ .map(|(app_slug, server_name)| AgentMcpServer {
+ app_slug,
+ server_name,
+ })
+ .collect();
+ let mcp = AgentMcpServers::from_columns(&row.mcp_scope, mcp_servers)?;
let bot = BotRow {
id: row.id,
kind: row.kind,
@@ -147,6 +163,7 @@ impl TryFrom<AgentRow> for Agent {
default_model: row.default_model,
channel_scope,
channel_ids: row.channel_ids,
+ mcp,
})
}
}
@@ -254,6 +271,33 @@ fn map_token_row(row: BotTokenRow) -> BotToken {
row.into()
}
+/// Writes an agent's selected MCP servers inside the caller's transaction.
+async fn insert_mcp_servers(
+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ bot_id: BotId,
+ servers: &[AgentMcpServer],
+) -> Result<(), anyhow::Error> {
+ if servers.is_empty() {
+ return Ok(());
+ }
+ let slugs: Vec<&str> = servers.iter().map(|s| s.app_slug.as_str()).collect();
+ let names: Vec<&str> = servers.iter().map(|s| s.server_name.as_str()).collect();
+ sqlx::query!(
+ r#"
+ INSERT INTO agent_mcp_servers (bot_id, app_slug, server_name)
+ SELECT $1, slug, name
+ FROM UNNEST($2::text[], $3::text[]) AS t(slug, name)
+ "#,
+ bot_id.as_uuid(),
+ &slugs as &[&str],
+ &names as &[&str],
+ )
+ .execute(&mut **tx)
+ .await
+ .context("failed to write the agent's MCP servers")?;
+ Ok(())
+}
+
impl BotRepo for PgBotsRepo {
type Err = anyhow::Error;
@@ -310,9 +354,9 @@ impl BotRepo for PgBotsRepo {
sqlx::query!(
r#"
INSERT INTO agent_configs (
- bot_id, instructions, harness, harness_id, default_model, channel_scope
+ bot_id, instructions, harness, harness_id, default_model, channel_scope, mcp_scope
)
- VALUES ($1, $2, $3, $4, $5, $6)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
"#,
bot_id.as_uuid(),
&req.instructions,
@@ -320,11 +364,14 @@ impl BotRepo for PgBotsRepo {
req.harness_id.map(HarnessId::as_uuid),
&req.default_model,
req.channel_scope.as_str(),
+ req.mcp.scope_str(),
)
.execute(&mut *tx)
.await
.context("failed to create agent config")?;
+ insert_mcp_servers(&mut tx, bot_id, req.mcp.servers()).await?;
+
if !req.channel_ids.is_empty() {
let bot_principal = principal_id(bot_id);
sqlx::query!(
@@ -353,6 +400,7 @@ impl BotRepo for PgBotsRepo {
default_model: req.default_model,
channel_scope: req.channel_scope,
channel_ids: req.channel_ids,
+ mcp: req.mcp,
})
}
@@ -422,6 +470,7 @@ impl BotRepo for PgBotsRepo {
harness_id = $4,
default_model = $5,
channel_scope = $6,
+ mcp_scope = $7,
updated_at = now()
WHERE bot_id = $1
"#,
@@ -431,11 +480,23 @@ impl BotRepo for PgBotsRepo {
req.harness_id.map(HarnessId::as_uuid),
&req.default_model,
req.channel_scope.as_str(),
+ req.mcp.scope_str(),
)
.execute(&mut *tx)
.await
.context("failed to update agent config")?;
+ // Replaced wholesale in the same transaction as the channels, so a
+ // reader never sees half of the old set and half of the new.
+ sqlx::query!(
+ "DELETE FROM agent_mcp_servers WHERE bot_id = $1",
+ bot_id.as_uuid(),
+ )
+ .execute(&mut *tx)
+ .await
+ .context("failed to clear the agent's previous MCP servers")?;
+ insert_mcp_servers(&mut tx, bot_id, req.mcp.servers()).await?;
+
let bot_principal = principal_id(bot_id);
sqlx::query!(
r#"
@@ -481,6 +542,7 @@ impl BotRepo for PgBotsRepo {
default_model: req.default_model,
channel_scope: req.channel_scope,
channel_ids: req.channel_ids,
+ mcp: req.mcp,
}))
}
@@ -516,7 +578,20 @@ impl BotRepo for PgBotsRepo {
WHERE p.user_id = 'bot|' || b.id::text
AND p.left_at IS NULL
ORDER BY p.channel_id
- ) AS "channel_ids!"
+ ) AS "channel_ids!",
+ a.mcp_scope,
+ ARRAY(
+ SELECT m.app_slug
+ FROM agent_mcp_servers m
+ WHERE m.bot_id = b.id
+ ORDER BY m.app_slug
+ ) AS "mcp_app_slugs!",
+ ARRAY(
+ SELECT m.server_name
+ FROM agent_mcp_servers m
+ WHERE m.bot_id = b.id
+ ORDER BY m.app_slug
+ ) AS "mcp_server_names!"
FROM bots b
INNER JOIN agent_configs a ON a.bot_id = b.id
WHERE b.kind = 'owned'
@@ -806,7 +881,20 @@ impl BotRepo for PgBotsRepo {
WHERE p.user_id = 'bot|' || b.id::text
AND p.left_at IS NULL
ORDER BY p.channel_id
- ) AS "channel_ids!"
+ ) AS "channel_ids!",
+ a.mcp_scope,
+ ARRAY(
+ SELECT m.app_slug
+ FROM agent_mcp_servers m
+ WHERE m.bot_id = b.id
+ ORDER BY m.app_slug
+ ) AS "mcp_app_slugs!",
+ ARRAY(
+ SELECT m.server_name
+ FROM agent_mcp_servers m
+ WHERE m.bot_id = b.id
+ ORDER BY m.app_slug
+ ) AS "mcp_server_names!"
FROM bots b
INNER JOIN agent_configs a ON a.bot_id = b.id
WHERE b.id = $1
diff --git a/crates/bots/src/outbound/pg_bots_repo/tests.rs b/crates/bots/src/outbound/pg_bots_repo/tests.rs
index 3d90f44c40..265edf9468 100644
--- a/crates/bots/src/outbound/pg_bots_repo/tests.rs
+++ b/crates/bots/src/outbound/pg_bots_repo/tests.rs
@@ -1,9 +1,9 @@
use super::*;
use crate::domain::{
models::{
- AgentChannelScope, BotChannelListCaller, BotChannelType, CreateAgentRequest,
- CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest, PatchBotRequest,
- UpdateAgentRequest,
+ AgentChannelScope, AgentMcpServer, AgentMcpServers, BotChannelListCaller, BotChannelType,
+ CreateAgentRequest, CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest,
+ PatchBotRequest, UpdateAgentRequest,
},
ports::{BotError, BotService},
service::BotServiceImpl,
@@ -82,6 +82,7 @@ fn create_agent_req(handle: &str, channel_scope: AgentChannelScope) -> CreateAge
default_model: "cursor-small".to_string(),
channel_scope,
channel_ids: Vec::new(),
+ mcp: AgentMcpServers::OwnerConnections,
}
}
@@ -98,6 +99,7 @@ fn update_agent_req(handle: &str, channel_scope: AgentChannelScope) -> UpdateAge
default_model: "claude-sonnet-4-5".to_string(),
channel_scope,
channel_ids: Vec::new(),
+ mcp: AgentMcpServers::OwnerConnections,
}
}
@@ -514,6 +516,157 @@ async fn updated_agent_replaces_every_field_and_selected_channel(
Ok(())
}
+fn mcp_server(app_slug: &str, server_name: &str) -> AgentMcpServer {
+ AgentMcpServer {
+ app_slug: app_slug.to_string(),
+ server_name: server_name.to_string(),
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn selected_mcp_servers_round_trip_and_are_replaced_wholesale(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let service = service(&pool);
+ let selected = |servers: Vec<AgentMcpServer>| AgentMcpServers::Selected { servers };
+ let mut create = create_agent_req("mcp-fixer", AgentChannelScope::All);
+ // Nothing here is connected for anyone: the persona picks from the whole
+ // catalog and the grant is the session owner's business.
+ create.mcp = selected(vec![
+ mcp_server("notion", "Notion"),
+ mcp_server("linear", "Linear"),
+ ]);
+ let created = service.create_agent(user_id(USER_OWNER), create).await?;
+ assert_eq!(
+ created.mcp,
+ selected(vec![
+ mcp_server("notion", "Notion"),
+ mcp_server("linear", "Linear"),
+ ])
+ );
+
+ let fetched = PgBotsRepo::new(pool.clone())
+ .get_agent(created.bot.id)
+ .await?
+ .expect("created agent should be addressable by bot id");
+ // Read back ordered by slug, whatever order they were written in.
+ assert_eq!(
+ fetched.mcp,
+ selected(vec![
+ mcp_server("linear", "Linear"),
+ mcp_server("notion", "Notion"),
+ ])
+ );
+ let listed = service.list_agents(user_id(USER_OWNER)).await?;
+ assert_eq!(listed[0].mcp, fetched.mcp);
+
+ let mut update = update_agent_req("mcp-fixer", AgentChannelScope::All);
+ update.mcp = selected(vec![mcp_server("hubspot", "HubSpot")]);
+ let updated = service
+ .update_agent(user_id(USER_OWNER), created.bot.id, update)
+ .await?;
+ assert_eq!(updated.mcp.servers(), [mcp_server("hubspot", "HubSpot")]);
+ let fetched = PgBotsRepo::new(pool.clone())
+ .get_agent(created.bot.id)
+ .await?
+ .expect("updated agent should still be addressable");
+ assert_eq!(fetched.mcp.servers(), [mcp_server("hubspot", "HubSpot")]);
+
+ let back_to_owner = update_agent_req("mcp-fixer", AgentChannelScope::All);
+ let reverted = service
+ .update_agent(user_id(USER_OWNER), created.bot.id, back_to_owner)
+ .await?;
+ assert_eq!(reverted.mcp, AgentMcpServers::OwnerConnections);
+ let rows = sqlx::query_scalar!(
+ r#"SELECT COUNT(*) AS "count!" FROM agent_mcp_servers WHERE bot_id = $1"#,
+ created.bot.id.as_uuid(),
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(rows, 0);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn mcp_server_selection_is_validated(pool: PgPool) -> anyhow::Result<()> {
+ let service = service(&pool);
+ let selected = |servers: Vec<AgentMcpServer>| AgentMcpServers::Selected { servers };
+
+ let mut bad_slug = create_agent_req("bad-mcp", AgentChannelScope::All);
+ bad_slug.mcp = selected(vec![mcp_server("Linear App", "Linear")]);
+ let error = service
+ .create_agent(user_id(USER_OWNER), bad_slug)
+ .await
+ .expect_err("a slug the proxy could never dial is refused");
+ assert!(matches!(error, BotError::BadRequest(_)));
+
+ let mut duplicate = create_agent_req("bad-mcp", AgentChannelScope::All);
+ duplicate.mcp = selected(vec![
+ mcp_server("linear", "Linear"),
+ mcp_server("linear", "Also"),
+ ]);
+ let error = service
+ .create_agent(user_id(USER_OWNER), duplicate)
+ .await
+ .expect_err("duplicate slugs are refused");
+ assert!(matches!(error, BotError::BadRequest(_)));
+
+ let mut unnamed = create_agent_req("bad-mcp", AgentChannelScope::All);
+ unnamed.mcp = selected(vec![mcp_server("linear", " ")]);
+ let error = service
+ .create_agent(user_id(USER_OWNER), unnamed)
+ .await
+ .expect_err("an unnamed server is refused");
+ assert!(matches!(error, BotError::BadRequest(_)));
+
+ // An explicit empty selection is a valid choice: this persona gets no
+ // connectors at all, not even the owner's.
+ let mut empty = create_agent_req("empty-mcp", AgentChannelScope::All);
+ empty.mcp = selected(Vec::new());
+ let created = service.create_agent(user_id(USER_OWNER), empty).await?;
+ assert_eq!(created.mcp, selected(Vec::new()));
+ Ok(())
+}
+
+#[test]
+fn agent_requests_without_mcp_fields_default_to_owner_connections() {
+ let legacy = json!({
+ "team_id": null,
+ "name": "Legacy",
+ "handle": "legacy",
+ "description": null,
+ "avatar_url": null,
+ "instructions": "",
+ "harness": "cursor",
+ "default_model": "cursor-small",
+ "channel_scope": "all",
+ });
+ let create: CreateAgentRequest = serde_json::from_value(legacy.clone()).unwrap();
+ assert_eq!(create.mcp, AgentMcpServers::OwnerConnections);
+ let update: UpdateAgentRequest = serde_json::from_value(legacy).unwrap();
+ assert_eq!(update.mcp, AgentMcpServers::OwnerConnections);
+}
+
+/// The wire shape is a tagged union, which is what the generated TypeScript
+/// consumes: the scope is the discriminator and the servers ride with it.
+#[test]
+fn agent_mcp_servers_serialize_as_a_tagged_union() {
+ let selected = AgentMcpServers::Selected {
+ servers: vec![mcp_server("linear", "Linear")],
+ };
+ assert_eq!(
+ serde_json::to_value(&selected).unwrap(),
+ json!({"scope": "selected", "servers": [{"app_slug": "linear", "server_name": "Linear"}]})
+ );
+ assert_eq!(
+ serde_json::to_value(AgentMcpServers::OwnerConnections).unwrap(),
+ json!({"scope": "owner_connections"})
+ );
+ let parsed: AgentMcpServers =
+ serde_json::from_value(json!({"scope": "selected", "servers": []})).unwrap();
+ assert_eq!(parsed, AgentMcpServers::Selected { servers: vec![] });
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn team_member_creator_can_change_agent_share_between_private_and_team(
pool: PgPool,
diff --git a/crates/macro_db_client/migrations/20260904180417_add_agent_mcp_servers.down.sql b/crates/macro_db_client/migrations/20260904180417_add_agent_mcp_servers.down.sql
new file mode 100644
index 0000000000..d35491f995
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260904180417_add_agent_mcp_servers.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE agent_configs DROP COLUMN mcp_scope;
+DROP TABLE agent_mcp_servers;
diff --git a/crates/macro_db_client/migrations/20260904180417_add_agent_mcp_servers.up.sql b/crates/macro_db_client/migrations/20260904180417_add_agent_mcp_servers.up.sql
new file mode 100644
index 0000000000..89e974c58e
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260904180417_add_agent_mcp_servers.up.sql
@@ -0,0 +1,21 @@
+-- Which Pipedream apps a persona hands its sessions, chosen from the whole
+-- Pipedream catalog whether or not anyone has connected them. The egress proxy
+-- resolves each slug against the session owner's own connections at call time
+-- and answers an unconnected one with a model-readable "not connected" result,
+-- so a selected app never needs a grant to be listed here.
+CREATE TABLE agent_mcp_servers (
+ bot_id uuid NOT NULL REFERENCES bots(id) ON DELETE CASCADE,
+ -- Pipedream's `name_slug`, verbatim; the same charset the proxy's
+ -- McpServerSlug::parse accepts, so every stored slug is dialable.
+ app_slug text NOT NULL CHECK (app_slug ~ '^[a-z0-9_-]+$'),
+ server_name text NOT NULL CHECK (server_name <> ''),
+ created_at timestamptz NOT NULL DEFAULT now(),
+ PRIMARY KEY (bot_id, app_slug)
+);
+
+-- 'owner_connections' keeps today's behaviour (advertise whatever the session
+-- owner has connected); 'selected' advertises exactly agent_mcp_servers.
+ALTER TABLE agent_configs
+ ADD COLUMN mcp_scope text NOT NULL DEFAULT 'owner_connections'
+ CONSTRAINT agent_configs_mcp_scope_valid
+ CHECK (mcp_scope IN ('owner_connections', 'selected'));
diff --git a/crates/macro_db_client/migrations/20260904181417_agent_session_mcp_servers.down.sql b/crates/macro_db_client/migrations/20260904181417_agent_session_mcp_servers.down.sql
new file mode 100644
index 0000000000..49f8c5f6e5
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260904181417_agent_session_mcp_servers.down.sql
@@ -0,0 +1,3 @@
+ALTER TABLE agent_session
+ DROP COLUMN mcp_servers,
+ DROP COLUMN mcp_scope;
diff --git a/crates/macro_db_client/migrations/20260904181417_agent_session_mcp_servers.up.sql b/crates/macro_db_client/migrations/20260904181417_agent_session_mcp_servers.up.sql
new file mode 100644
index 0000000000..129698583f
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260904181417_agent_session_mcp_servers.up.sql
@@ -0,0 +1,11 @@
+-- Snapshot of the agent's MCP policy at session creation, like `instructions`:
+-- the ACP agent is handed its server list once per attach and cannot refresh
+-- it, so the egress proxy must enforce exactly what was advertised for the
+-- session's whole life. Editing the agent applies to its next session.
+ALTER TABLE agent_session
+ ADD COLUMN mcp_scope text NOT NULL DEFAULT 'owner_connections'
+ CONSTRAINT agent_session_mcp_scope_valid
+ CHECK (mcp_scope IN ('owner_connections', 'selected')),
+ -- [{"app_slug": "linear", "server_name": "Linear"}, ...]; empty unless
+ -- mcp_scope is 'selected'.
+ ADD COLUMN mcp_servers jsonb NOT NULL DEFAULT '[]'::jsonb;
diff --git a/crates/mcp_select/src/lib.rs b/crates/mcp_select/src/lib.rs
index e570bbc456..d2934dbf0b 100644
--- a/crates/mcp_select/src/lib.rs
+++ b/crates/mcp_select/src/lib.rs
@@ -91,6 +91,10 @@ impl<Context: Send + Sync + 'static> ToolSet<Context> for UserMcpTools {
}
}
+ fn searchable_catalog(&self) -> Vec<SearchableTool> {
+ self.catalog()
+ }
+
fn searchable_toolset_names(&self) -> Vec<String> {
match self {
UserMcpTools::Pipedream(tools) => ToolSet::<Context>::searchable_toolset_names(tools),
@@ -273,16 +277,19 @@ where
}
}
-/// Wraps a static [`AsyncToolCollection`] and the user's selected MCP tools,
-/// presenting them as a single toolset to the AI loop.
-pub struct CombinedToolSet<T> {
+/// Wraps a static [`AsyncToolCollection`] and a set of MCP tools, presenting
+/// them as a single toolset to the AI loop.
+///
+/// `Mcp` defaults to the per-user selection, [`UserMcpTools`]; the in-process
+/// agent runtime composes the same way over the servers it was handed.
+pub struct CombinedToolSet<T, Mcp = UserMcpTools> {
static_tools: Arc<AsyncToolCollection<T>>,
- mcp_tools: UserMcpTools,
+ mcp_tools: Mcp,
}
-impl<T> CombinedToolSet<T> {
- /// Combine the static tools with an already-selected MCP toolset.
- pub fn new(static_tools: Arc<AsyncToolCollection<T>>, mcp_tools: UserMcpTools) -> Self {
+impl<T, Mcp> CombinedToolSet<T, Mcp> {
+ /// Combine the static tools with an already-built MCP toolset.
+ pub fn new(static_tools: Arc<AsyncToolCollection<T>>, mcp_tools: Mcp) -> Self {
Self {
static_tools,
mcp_tools,
@@ -290,7 +297,7 @@ impl<T> CombinedToolSet<T> {
}
}
-impl<T: Send + Sync + 'static> ToolSet<T> for CombinedToolSet<T> {
+impl<T: Send + Sync + 'static, Mcp: ToolSet<T>> ToolSet<T> for CombinedToolSet<T, Mcp> {
fn try_tool_call<'a>(
&'a self,
context: T,
@@ -318,7 +325,7 @@ impl<T: Send + Sync + 'static> ToolSet<T> for CombinedToolSet<T> {
}
fn searchable_catalog(&self) -> Vec<SearchableTool> {
- self.mcp_tools.catalog()
+ ToolSet::<T>::searchable_catalog(&self.mcp_tools)
}
fn searchable_toolset_names(&self) -> Vec<String> {
diff --git a/crates/mcp_toolset/Cargo.toml b/crates/mcp_toolset/Cargo.toml
new file mode 100644
index 0000000000..0b659d0a10
--- /dev/null
+++ b/crates/mcp_toolset/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "mcp_toolset"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+ai_toolset = { path = "../ai_toolset" }
+anyhow.workspace = true
+futures.workspace = true
+rmcp = { workspace = true, features = ["client"] }
+schemars.workspace = true
+serde_json.workspace = true
+thiserror.workspace = true
+tracing.workspace = true
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+regex.workspace = true
diff --git a/crates/pipedream_mcp/src/domain/call_tool_result.rs b/crates/mcp_toolset/src/call_tool_result.rs
similarity index 100%
rename from crates/pipedream_mcp/src/domain/call_tool_result.rs
rename to crates/mcp_toolset/src/call_tool_result.rs
diff --git a/crates/pipedream_mcp/src/domain/call_tool_result/test.rs b/crates/mcp_toolset/src/call_tool_result/test.rs
similarity index 100%
rename from crates/pipedream_mcp/src/domain/call_tool_result/test.rs
rename to crates/mcp_toolset/src/call_tool_result/test.rs
diff --git a/crates/mcp_toolset/src/lib.rs b/crates/mcp_toolset/src/lib.rs
new file mode 100644
index 0000000000..2b41e282b1
--- /dev/null
+++ b/crates/mcp_toolset/src/lib.rs
@@ -0,0 +1,36 @@
+#![deny(missing_docs)]
+//! An [`ai_toolset::ToolSet`] over already-connected MCP servers.
+//!
+//! Every MCP-backed toolset in Macro needs the same three things once it has
+//! live sessions in hand: list each server's tools, expose them under
+//! provider-safe mangled names (`mcp__<server>__<tool>`), and route a call by
+//! that name back to the right peer with the tool's real name. This crate is
+//! that shared piece, and nothing else - it does not know how a session was
+//! opened. `pipedream_mcp` connects through Pipedream's remote server and the
+//! in-process agent runtime dials the servers it was handed over ACP; both
+//! end here.
+
+mod call_tool_result;
+mod mangle;
+mod toolset;
+
+pub use call_tool_result::CallToolResultExt;
+pub use toolset::{ConnectedServer, Error, RemoteMcpToolSet};
+
+use rmcp::RoleClient;
+use rmcp::model::{ClientInfo, Implementation};
+use rmcp::service::RunningService;
+
+/// Our MCP client publishes this name to servers on-connect.
+pub const MCP_CLIENT_NAME: &str = "Macro";
+
+/// 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")),
+ )
+}
diff --git a/crates/mcp_toolset/src/mangle.rs b/crates/mcp_toolset/src/mangle.rs
new file mode 100644
index 0000000000..78d3e6542e
--- /dev/null
+++ b/crates/mcp_toolset/src/mangle.rs
@@ -0,0 +1,141 @@
+//! Provider-safe tool names for MCP tools.
+//!
+//! Every tool is exposed as `mcp__<server>__<tool>` so names stay unique
+//! across servers and can be routed back without a lookup table.
+
+#[cfg(test)]
+mod test;
+
+const MANGLED_PREFIX: &str = "mcp__";
+const MANGLED_SEPARATOR: &str = "__";
+/// Model providers reject tool names that do not match
+/// `^[a-zA-Z0-9_-]{1,128}$`, and they validate the whole tool array: a single
+/// malformed name fails every request in the conversation, not just calls to
+/// that tool.
+const MAX_MANGLED_LEN: usize = 128;
+/// Substituted when the server segment sanitizes to nothing, so a mangled
+/// name can never contain an empty segment.
+const EMPTY_SERVER_SEGMENT: &str = "server";
+/// Substituted when the tool segment sanitizes to nothing.
+const EMPTY_TOOL_SEGMENT: &str = "tool";
+/// Floor for truncating the server segment, so a very long tool name cannot
+/// squeeze the server segment down to nothing. Must exceed both placeholders.
+const MIN_TRUNCATED_SEGMENT: usize = 8;
+
+/// The characters model providers accept in a tool name.
+fn is_allowed(c: char) -> bool {
+ c.is_ascii_alphanumeric() || c == '_' || c == '-'
+}
+
+/// Replaces every run of disallowed characters with a single `_` and trims
+/// leading and trailing underscores.
+///
+/// `collapse_underscores` additionally collapses runs of underscores into one.
+/// The server segment needs that: [`MangledName::parse`] splits on the first
+/// `__`, so a server segment containing `__` would make the split report the
+/// wrong server name.
+fn sanitize_segment(raw: &str, collapse_underscores: bool) -> String {
+ let mut out = String::with_capacity(raw.len());
+ let mut in_disallowed_run = false;
+ for c in raw.chars() {
+ let next = if is_allowed(c) {
+ in_disallowed_run = false;
+ c
+ } else if in_disallowed_run {
+ continue;
+ } else {
+ in_disallowed_run = true;
+ '_'
+ };
+ if collapse_underscores && next == '_' && out.ends_with('_') {
+ continue;
+ }
+ out.push(next);
+ }
+ out.trim_matches('_').to_owned()
+}
+
+/// Shortens an already sanitized (so ASCII) segment to at most `max` bytes,
+/// dropping any underscore left dangling at the cut and falling back to
+/// `placeholder` if nothing survives.
+fn fit_segment(segment: &mut String, max: usize, placeholder: &str) {
+ if segment.len() <= max {
+ return;
+ }
+ segment.truncate(max);
+ while segment.ends_with('_') {
+ segment.pop();
+ }
+ if segment.is_empty() {
+ segment.push_str(placeholder);
+ }
+}
+
+/// A mangled tool name plus whether sanitizing had to change it.
+pub(crate) struct Mangled {
+ /// The sanitized name, always matching `^[a-zA-Z0-9_-]{1,128}$`.
+ pub(crate) name: MangledName,
+ /// Set when the sanitized name differs from the raw `server__tool` join,
+ /// i.e. the raw names would have been rejected by the provider.
+ pub(crate) sanitized: bool,
+}
+
+/// A mangled tool name in the format `mcp__<server>__<tool>`.
+#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub(crate) struct MangledName(pub(crate) String);
+
+impl Mangled {
+ /// Builds `mcp__<server>__<tool>`, sanitizing both segments so the result
+ /// always matches `^[a-zA-Z0-9_-]{1,128}$`.
+ ///
+ /// Server names are human-readable display names (`Google Sheets`), so
+ /// they routinely contain characters providers reject. Sanitizing here
+ /// rather than where the name is written also covers names already
+ /// persisted, and keeps every future source of the name covered.
+ ///
+ /// Truncation is safe for dispatch: the unmangled tool name is kept on
+ /// the registered tool and is what gets sent to the peer.
+ pub(crate) fn new(server_name: &str, tool_name: &str) -> Self {
+ let mut server = sanitize_segment(server_name, true);
+ let mut tool = sanitize_segment(tool_name, false);
+
+ if server.is_empty() {
+ server = EMPTY_SERVER_SEGMENT.to_owned();
+ }
+ if tool.is_empty() {
+ tool = EMPTY_TOOL_SEGMENT.to_owned();
+ }
+
+ let budget = MAX_MANGLED_LEN - MANGLED_PREFIX.len() - MANGLED_SEPARATOR.len();
+ if server.len() + tool.len() > budget {
+ let server_max = budget.saturating_sub(tool.len()).max(MIN_TRUNCATED_SEGMENT);
+ fit_segment(&mut server, server_max, EMPTY_SERVER_SEGMENT);
+ }
+ if server.len() + tool.len() > budget {
+ fit_segment(&mut tool, budget - server.len(), EMPTY_TOOL_SEGMENT);
+ }
+
+ let sanitized = server != server_name || tool != tool_name;
+ Self {
+ name: MangledName(format!("{MANGLED_PREFIX}{server}{MANGLED_SEPARATOR}{tool}")),
+ sanitized,
+ }
+ }
+}
+
+impl MangledName {
+ pub(crate) fn parse(s: &str) -> Option<(&str, &str)> {
+ s.strip_prefix(MANGLED_PREFIX)?
+ .split_once(MANGLED_SEPARATOR)
+ }
+
+ pub(crate) 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)
+ }
+}
diff --git a/crates/pipedream_mcp/src/domain/service/toolset/test.rs b/crates/mcp_toolset/src/mangle/test.rs
similarity index 100%
rename from crates/pipedream_mcp/src/domain/service/toolset/test.rs
rename to crates/mcp_toolset/src/mangle/test.rs
diff --git a/crates/mcp_toolset/src/toolset.rs b/crates/mcp_toolset/src/toolset.rs
new file mode 100644
index 0000000000..a9bff2128e
--- /dev/null
+++ b/crates/mcp_toolset/src/toolset.rs
@@ -0,0 +1,278 @@
+//! The toolset over connected servers.
+
+use crate::McpServer;
+use crate::call_tool_result::CallToolResultExt;
+use crate::mangle::{Mangled, MangledName};
+use ai_toolset::{
+ RequestContext, RequestSchema, SearchableTool, ToolCallError, ToolInfo, ToolResult, ToolSet,
+ ToolSetError,
+};
+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;
+
+/// Errors from MCP tool dispatch.
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ /// 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),
+}
+
+/// One live server and the name its tools are exposed under.
+pub struct ConnectedServer {
+ /// The server segment of every mangled name, e.g. `Linear`.
+ pub name: String,
+ /// The open session, kept alive for as long as the toolset is.
+ pub client: McpServer,
+}
+
+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.
+///
+/// Cheap to clone: every clone shares the same live sessions, which stay open
+/// until the last clone is dropped. A host that keeps one across turns hands
+/// out clones and composes them like any other toolset.
+#[derive(Clone)]
+pub struct RemoteMcpToolSet(Arc<Registered>);
+
+struct Registered {
+ tools: BTreeMap<MangledName, RegisteredTool>,
+ /// Kept alive so the background transport tasks aren't cancelled.
+ _connections: Vec<McpServer>,
+ /// Who the servers belong to, for correlating tool-call failures in logs.
+ subject: Option<String>,
+}
+
+impl RemoteMcpToolSet {
+ /// Discover every server's tools and register them.
+ ///
+ /// `subject` names whose servers these are, for logs only. A server that
+ /// fails to list its tools is skipped with a warning: one bad server must
+ /// not take the others' tools with it.
+ #[tracing::instrument(skip_all, fields(servers = servers.len(), subject = ?subject))]
+ pub async fn from_connected(servers: Vec<ConnectedServer>, subject: Option<String>) -> Self {
+ let listings = futures::future::join_all(servers.into_iter().map(|server| async move {
+ match server.client.list_all_tools().await {
+ Ok(tools) => Some((server.name, server.client, tools)),
+ Err(error) => {
+ tracing::warn!(
+ server = %server.name,
+ error = ?error,
+ "failed to list tools; skipping the server"
+ );
+ let _ = server.client.cancel().await;
+ None
+ }
+ }
+ }))
+ .await;
+
+ let mut tools = BTreeMap::new();
+ let mut connections = Vec::new();
+ for (server_name, client, server_tools) in listings.into_iter().flatten() {
+ for tool in server_tools {
+ let Mangled {
+ name: mangled,
+ sanitized,
+ } = Mangled::new(&server_name, &tool.name);
+
+ if sanitized {
+ tracing::warn!(
+ subject = ?subject,
+ server = %server_name,
+ tool = %tool.name,
+ %mangled,
+ "sanitized tool name to satisfy the provider tool-name pattern"
+ );
+ }
+
+ if tools.contains_key(&mangled) {
+ tracing::warn!(
+ subject = ?subject,
+ server = %server_name,
+ tool = %tool.name,
+ %mangled,
+ "skipping duplicate tool"
+ );
+ continue;
+ }
+
+ tools.insert(
+ mangled,
+ RegisteredTool {
+ peer: client.peer().clone(),
+ tool,
+ },
+ );
+ }
+ connections.push(client);
+ }
+
+ Self(Arc::new(Registered {
+ tools,
+ _connections: connections,
+ subject,
+ }))
+ }
+
+ /// Returns `true` when no tools were discovered.
+ pub fn is_empty(&self) -> bool {
+ self.0.tools.is_empty()
+ }
+
+ /// The full catalog of MCP tools (mangled name + description + input
+ /// schema) for on-demand loading via tool search.
+ pub fn searchable_catalog(&self) -> Vec<SearchableTool> {
+ self.0
+ .tools
+ .iter()
+ .map(|(mangled, entry)| SearchableTool {
+ name: mangled.as_str().to_string(),
+ description: entry
+ .tool
+ .description
+ .as_deref()
+ .unwrap_or_default()
+ .to_string(),
+ schema: Schema::from((*entry.tool.input_schema).clone()),
+ })
+ .collect()
+ }
+
+ /// Distinct names of the connected MCP servers that contributed tools,
+ /// sorted for a stable prompt. Derived from the mangled tool keys so it
+ /// reflects the servers actually serving searchable tools this request.
+ fn toolset_names(&self) -> Vec<String> {
+ let mut names: Vec<String> = self
+ .0
+ .tools
+ .keys()
+ .filter_map(|mangled| MangledName::parse(mangled.as_str()))
+ .map(|(server, _tool)| server.to_string())
+ .collect();
+ names.sort();
+ names.dedup();
+ names
+ }
+
+ #[tracing::instrument(skip(self, arguments), err, fields(subject = ?self.0.subject))]
+ 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
+ .0
+ .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 RemoteMcpToolSet {
+ 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 = match self.call_tool(tool_name, arguments).await {
+ Ok(result) => result,
+ Err(Error::UnknownTool(name)) => {
+ return Err(ToolSetError::NotFound(name));
+ }
+ Err(e) => {
+ let description = e.to_string();
+ return Ok(Err(ToolCallError {
+ internal_error: anyhow::anyhow!("{}", &description),
+ description,
+ }));
+ }
+ };
+
+ if result.is_error.unwrap_or(false) {
+ let description = result.error_description();
+ Ok(Err(ToolCallError {
+ internal_error: anyhow::anyhow!("{}", &description),
+ description,
+ }))
+ } else {
+ Ok(Ok(result.into_value()))
+ }
+ })
+ }
+
+ fn request_schemas(&self) -> Option<Vec<RequestSchema>> {
+ let schemas: Vec<_> = self
+ .0
+ .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 searchable_catalog(&self) -> Vec<SearchableTool> {
+ RemoteMcpToolSet::searchable_catalog(self)
+ }
+
+ fn searchable_toolset_names(&self) -> Vec<String> {
+ self.toolset_names()
+ }
+
+ fn routing_description<'a>(&'a self, tool_name: &'a str) -> Option<ToolInfo> {
+ let (server_name, original_name) = MangledName::parse(tool_name)?;
+ let key = MangledName(tool_name.to_owned());
+ let display_name = self
+ .0
+ .tools
+ .get(&key)
+ .and_then(|entry| entry.tool.title.clone());
+ Some(ToolInfo::ExternalTool {
+ service_name: server_name.to_owned(),
+ tool_name: original_name.to_owned(),
+ display_name,
+ })
+ }
+}
diff --git a/crates/pipedream_mcp/Cargo.toml b/crates/pipedream_mcp/Cargo.toml
index c6c9b68277..f453a26902 100644
--- a/crates/pipedream_mcp/Cargo.toml
+++ b/crates/pipedream_mcp/Cargo.toml
@@ -13,6 +13,7 @@ macro_authorization = { path = "../macro_authorization", default-features = fals
"axum",
] }
macro_user_id = { path = "../macro_user_id" }
+mcp_toolset = { path = "../mcp_toolset" }
model-error-response = { path = "../model-error-response" }
reqwest.workspace = true
url.workspace = true
@@ -27,5 +28,4 @@ utoipa.workspace = true
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
-regex.workspace = true
tokio.workspace = true
diff --git a/crates/pipedream_mcp/src/domain/mod.rs b/crates/pipedream_mcp/src/domain/mod.rs
index 99030608a3..1242202c6a 100644
--- a/crates/pipedream_mcp/src/domain/mod.rs
+++ b/crates/pipedream_mcp/src/domain/mod.rs
@@ -1,7 +1,6 @@
-mod call_tool_result;
/// Domain models for Pipedream connections and the app catalog.
pub mod models;
-pub use call_tool_result::CallToolResultExt;
+pub use mcp_toolset::CallToolResultExt;
/// Port traits consumed by the domain services.
pub mod ports;
/// Domain services: connect completion, catalog browsing, and the toolset.
diff --git a/crates/pipedream_mcp/src/domain/models.rs b/crates/pipedream_mcp/src/domain/models.rs
index 8160ac7347..b031d8e07f 100644
--- a/crates/pipedream_mcp/src/domain/models.rs
+++ b/crates/pipedream_mcp/src/domain/models.rs
@@ -1,22 +1,5 @@
-use rmcp::RoleClient;
-use rmcp::model::{ClientInfo, Implementation};
-use rmcp::service::RunningService;
-
pub use macro_user_id::user_id::MacroUserIdStr;
-
-/// Our MCP client publishes this name to servers on-connect.
-pub const MCP_CLIENT_NAME: &str = "Macro";
-
-/// 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")),
- )
-}
+pub use mcp_toolset::{MCP_CLIENT_NAME, McpServer, client_info};
/// An MCP connector a user has connected through Pipedream.
///
@@ -86,12 +69,4 @@ pub struct CatalogPage {
}
/// Errors from Pipedream MCP tool dispatch.
-#[derive(Debug, thiserror::Error)]
-pub enum Error {
- /// 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),
-}
+pub use mcp_toolset::Error;
diff --git a/crates/pipedream_mcp/src/domain/service/toolset.rs b/crates/pipedream_mcp/src/domain/service/toolset.rs
index a7c9031241..3c797d82e7 100644
--- a/crates/pipedream_mcp/src/domain/service/toolset.rs
+++ b/crates/pipedream_mcp/src/domain/service/toolset.rs
@@ -1,186 +1,32 @@
-use crate::domain::CallToolResultExt;
-use crate::domain::models::{Error, MacroUserIdStr, McpServer, PipedreamConnection};
+use crate::domain::models::PipedreamConnection;
use crate::domain::ports::McpConnection;
use ai_toolset::{
- RequestContext, RequestSchema, SearchableTool, ToolCallError, ToolInfo, ToolResult, ToolSet,
- ToolSetError,
+ RequestContext, RequestSchema, SearchableTool, ToolInfo, ToolResult, ToolSet, ToolSetError,
};
-use rmcp::RoleClient;
-use rmcp::model::{CallToolRequestParams, CallToolResult, Tool};
-use rmcp::service::Peer;
-use schemars::Schema;
-use std::collections::BTreeMap;
+use mcp_toolset::{ConnectedServer, RemoteMcpToolSet};
use std::pin::Pin;
use std::sync::Arc;
-#[cfg(test)]
-mod test;
-
-const MANGLED_PREFIX: &str = "mcp__";
-const MANGLED_SEPARATOR: &str = "__";
-/// Model providers reject tool names that do not match
-/// `^[a-zA-Z0-9_-]{1,128}$`, and they validate the whole tool array: a single
-/// malformed name fails every request in the conversation, not just calls to
-/// that tool.
-const MAX_MANGLED_LEN: usize = 128;
-/// Substituted when the server segment sanitizes to nothing, so a mangled
-/// name can never contain an empty segment.
-const EMPTY_SERVER_SEGMENT: &str = "server";
-/// Substituted when the tool segment sanitizes to nothing.
-const EMPTY_TOOL_SEGMENT: &str = "tool";
-/// Floor for truncating the server segment, so a very long tool name cannot
-/// squeeze the server segment down to nothing. Must exceed both placeholders.
-const MIN_TRUNCATED_SEGMENT: usize = 8;
-
-/// The characters model providers accept in a tool name.
-fn is_allowed(c: char) -> bool {
- c.is_ascii_alphanumeric() || c == '_' || c == '-'
-}
-
-/// Replaces every run of disallowed characters with a single `_` and trims
-/// leading and trailing underscores.
-///
-/// `collapse_underscores` additionally collapses runs of underscores into one.
-/// The server segment needs that: [`MangledName::parse`] splits on the first
-/// `__`, so a server segment containing `__` would make the split report the
-/// wrong server name.
-fn sanitize_segment(raw: &str, collapse_underscores: bool) -> String {
- let mut out = String::with_capacity(raw.len());
- let mut in_disallowed_run = false;
- for c in raw.chars() {
- let next = if is_allowed(c) {
- in_disallowed_run = false;
- c
- } else if in_disallowed_run {
- continue;
- } else {
- in_disallowed_run = true;
- '_'
- };
- if collapse_underscores && next == '_' && out.ends_with('_') {
- continue;
- }
- out.push(next);
- }
- out.trim_matches('_').to_owned()
-}
-
-/// Shortens an already sanitized (so ASCII) segment to at most `max` bytes,
-/// dropping any underscore left dangling at the cut and falling back to
-/// `placeholder` if nothing survives.
-fn fit_segment(segment: &mut String, max: usize, placeholder: &str) {
- if segment.len() <= max {
- return;
- }
- segment.truncate(max);
- while segment.ends_with('_') {
- segment.pop();
- }
- if segment.is_empty() {
- segment.push_str(placeholder);
- }
-}
-
-/// A mangled tool name plus whether sanitizing had to change it.
-struct Mangled {
- /// The sanitized name, always matching `^[a-zA-Z0-9_-]{1,128}$`.
- name: MangledName,
- /// Set when the sanitized name differs from the raw `server__tool` join,
- /// i.e. the raw names would have been rejected by the provider.
- sanitized: bool,
-}
-
-/// A mangled tool name in the format `mcp__<server>__<tool>`.
-#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
-struct MangledName(String);
-
-impl Mangled {
- /// Builds `mcp__<server>__<tool>`, sanitizing both segments so the result
- /// always matches `^[a-zA-Z0-9_-]{1,128}$`.
- ///
- /// Server names are human-readable display names (`Google Sheets`), so
- /// they routinely contain characters providers reject. Sanitizing here
- /// rather than where the name is written also covers names already
- /// persisted, and keeps every future source of the name covered.
- ///
- /// Truncation is safe for dispatch: the unmangled tool name is kept on
- /// [`RegisteredTool`] and is what gets sent to the peer.
- fn new(server_name: &str, tool_name: &str) -> Self {
- let mut server = sanitize_segment(server_name, true);
- let mut tool = sanitize_segment(tool_name, false);
-
- if server.is_empty() {
- server = EMPTY_SERVER_SEGMENT.to_owned();
- }
- if tool.is_empty() {
- tool = EMPTY_TOOL_SEGMENT.to_owned();
- }
-
- let budget = MAX_MANGLED_LEN - MANGLED_PREFIX.len() - MANGLED_SEPARATOR.len();
- if server.len() + tool.len() > budget {
- let server_max = budget.saturating_sub(tool.len()).max(MIN_TRUNCATED_SEGMENT);
- fit_segment(&mut server, server_max, EMPTY_SERVER_SEGMENT);
- }
- if server.len() + tool.len() > budget {
- fit_segment(&mut tool, budget - server.len(), EMPTY_TOOL_SEGMENT);
- }
-
- let sanitized = server != server_name || tool != tool_name;
- Self {
- name: MangledName(format!("{MANGLED_PREFIX}{server}{MANGLED_SEPARATOR}{tool}")),
- sanitized,
- }
- }
-}
-
-impl MangledName {
- fn parse(s: &str) -> Option<(&str, &str)> {
- s.strip_prefix(MANGLED_PREFIX)?
- .split_once(MANGLED_SEPARATOR)
- }
-
- 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.
+/// The tools of a user's Pipedream-connected apps.
///
-/// Every tool is exposed as `mcp__<server_name>__<tool_name>` to guarantee
-/// uniqueness across servers.
-pub struct PipedreamToolSet {
- tools: BTreeMap<MangledName, RegisteredTool>,
- /// Kept alive so the background transport tasks aren't cancelled.
- _connections: Vec<McpServer>,
- /// The owning user, for correlating tool-call failures in logs. All
- /// records passed to [`PipedreamToolSet::new`] belong to one user in practice.
- user_id: Option<MacroUserIdStr<'static>>,
-}
+/// Connecting is this crate's business - one session per enabled app through
+/// Pipedream's remote MCP server, which injects the account's credentials
+/// server-side. Everything after the connections are open (tool discovery,
+/// name mangling, dispatch) is [`RemoteMcpToolSet`]'s, shared with every
+/// other MCP-backed toolset.
+pub struct PipedreamToolSet(RemoteMcpToolSet);
impl PipedreamToolSet {
- /// Connect to every app in `records` concurrently, discover tools, and
- /// register them. Connections go through `connection` (Pipedream's
- /// remote MCP server), which injects each account's credentials
- /// server-side.
+ /// Connect to every enabled app in `records` concurrently, discover
+ /// tools, and register them.
///
- /// Apps that fail to connect or list tools are silently skipped.
+ /// Apps that fail to connect or list tools are skipped with a warning.
#[tracing::instrument(skip_all)]
pub async fn new<C: McpConnection>(
records: &[PipedreamConnection],
connection: Arc<C>,
) -> Self {
- let user_id = records.first().map(|r| r.user_id.clone());
+ let user_id = records.first().map(|r| r.user_id.to_string());
let futs = records.iter().filter(|r| r.enabled).map(|record| {
let connection = connection.clone();
@@ -198,223 +44,60 @@ impl PipedreamToolSet {
);
})
.ok()?;
-
- let server_tools = match client.list_all_tools().await {
- Ok(t) => t,
- Err(e) => {
- tracing::warn!(
- user_id = %record.user_id,
- server = %record.server_name,
- app = %record.app_slug,
- error = ?e,
- "failed to list tools"
- );
- let _ = client.cancel().await;
- return None;
- }
- };
-
- Some((
- record.server_name.clone(),
- record.app_slug.clone(),
+ Some(ConnectedServer {
+ name: record.server_name.clone(),
client,
- server_tools,
- ))
+ })
}
});
+ let servers: Vec<ConnectedServer> = futures::future::join_all(futs)
+ .await
+ .into_iter()
+ .flatten()
+ .collect();
- let results = futures::future::join_all(futs).await;
-
- let mut tools = BTreeMap::new();
- let mut connections = Vec::new();
- for (server_name, app_slug, client, server_tools) in results.into_iter().flatten() {
- for tool in server_tools {
- let Mangled {
- name: mangled,
- sanitized,
- } = Mangled::new(&server_name, &tool.name);
-
- if sanitized {
- tracing::warn!(
- user_id = ?user_id,
- server = %server_name,
- app = %app_slug,
- tool = %tool.name,
- %mangled,
- "sanitized tool name to satisfy the provider tool-name pattern"
- );
- }
-
- if tools.contains_key(&mangled) {
- tracing::warn!(
- user_id = ?user_id,
- server = %server_name,
- app = %app_slug,
- tool = %tool.name,
- %mangled,
- "skipping duplicate tool"
- );
- continue;
- }
-
- tools.insert(
- mangled,
- RegisteredTool {
- peer: client.peer().clone(),
- tool,
- },
- );
- }
- connections.push(client);
- }
-
- Self {
- tools,
- _connections: connections,
- user_id,
- }
+ Self(RemoteMcpToolSet::from_connected(servers, user_id).await)
}
/// Returns `true` when no tools were discovered.
pub fn is_empty(&self) -> bool {
- self.tools.is_empty()
+ self.0.is_empty()
}
/// The full catalog of MCP tools, public for hosts that compose this
/// toolset (see the `mcp_select` crate).
pub fn searchable_catalog(&self) -> Vec<SearchableTool> {
- self.catalog()
- }
-
- /// The full catalog of MCP tools (mangled name + description + input schema)
- /// for on-demand loading via tool search.
- fn catalog(&self) -> Vec<SearchableTool> {
- self.tools
- .iter()
- .map(|(mangled, entry)| SearchableTool {
- name: mangled.as_str().to_string(),
- description: entry
- .tool
- .description
- .as_deref()
- .unwrap_or_default()
- .to_string(),
- schema: Schema::from((*entry.tool.input_schema).clone()),
- })
- .collect()
- }
-
- /// Distinct names of the connected MCP servers that contributed tools,
- /// sorted for a stable prompt. Derived from the mangled tool keys so it
- /// reflects the servers actually serving searchable tools this request.
- fn toolset_names(&self) -> Vec<String> {
- let mut names: Vec<String> = self
- .tools
- .keys()
- .filter_map(|mangled| MangledName::parse(mangled.as_str()))
- .map(|(server, _tool)| server.to_string())
- .collect();
- names.sort();
- names.dedup();
- names
- }
-
- #[tracing::instrument(skip(self, arguments), err, fields(user_id = ?self.user_id))]
- 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()))
+ self.0.searchable_catalog()
}
}
impl<Context: Send + Sync + 'static> ToolSet<Context> for PipedreamToolSet {
fn try_tool_call<'a>(
&'a self,
- _context: Context,
- _request_context: RequestContext,
+ 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 = match self.call_tool(tool_name, arguments).await {
- Ok(result) => result,
- Err(Error::UnknownTool(name)) => {
- return Err(ToolSetError::NotFound(name));
- }
- Err(e) => {
- let description = e.to_string();
- return Ok(Err(ToolCallError {
- internal_error: anyhow::anyhow!("{}", &description),
- description,
- }));
- }
- };
-
- if result.is_error.unwrap_or(false) {
- let description = result.error_description();
- Ok(Err(ToolCallError {
- internal_error: anyhow::anyhow!("{}", &description),
- description,
- }))
- } else {
- Ok(Ok(result.into_value()))
- }
- })
+ self.0
+ .try_tool_call(context, request_context, tool_name, json)
}
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();
+ ToolSet::<Context>::request_schemas(&self.0)
+ }
- if schemas.is_empty() {
- None
- } else {
- Some(schemas)
- }
+ fn searchable_catalog(&self) -> Vec<SearchableTool> {
+ self.0.searchable_catalog()
}
fn searchable_toolset_names(&self) -> Vec<String> {
- self.toolset_names()
+ ToolSet::<Context>::searchable_toolset_names(&self.0)
}
fn routing_description<'a>(&'a self, tool_name: &'a str) -> Option<ToolInfo> {
- let (server_name, original_name) = MangledName::parse(tool_name)?;
- let key = MangledName(tool_name.to_owned());
- let display_name = self
- .tools
- .get(&key)
- .and_then(|entry| entry.tool.title.clone());
- Some(ToolInfo::ExternalTool {
- service_name: server_name.to_owned(),
- tool_name: original_name.to_owned(),
- display_name,
- })
+ ToolSet::<Context>::routing_description(&self.0, tool_name)
}
}
diff --git a/crates/prompt/src/mentions.rs b/crates/prompt/src/mentions.rs
index a101241676..58f1640159 100644
--- a/crates/prompt/src/mentions.rs
+++ b/crates/prompt/src/mentions.rs
@@ -33,6 +33,8 @@ The AI does not need to know the name — an empty string is fine and the fronte
- Calendar event mention: `<m-document-mention>{"documentId":"{event_id}","documentName":"","blockName":"calendar","blockParams":{}}</m-document-mention>`
- Calendar event occurrence mention: `<m-document-mention>{"documentId":"{event_id}","documentName":"","blockName":"calendar","blockParams":{"occurrenceKey":"{recurrence_id}"}}</m-document-mention>`
+If a tool result tells you an app is not connected for the person you are working for and hands you a `<m-connect-app>{"appSlug":"...","name":"..."}</m-connect-app>` tag, include that tag verbatim in your reply: it renders as a button that connects the app. Never invent one; only repeat the tag a tool result gave you. End that reply by asking them to let you know once they have connected the app so you can try again.
+
The `blockName` for an email thread is always exactly `email` — never `thread` or `email_thread`, which the frontend cannot resolve.
The `blockName` for a calendar event is always exactly `calendar` — never `calendar_event`, which the frontend cannot resolve. `documentId` is the `eventId` a calendar tool returned. To point at one instance of a recurring event, pass that occurrence's `recurrenceId` from ListCalendarEvents as the `occurrenceKey` block param; otherwise omit it and the mention previews the nearest instance. A calendar event mention resolves only for users who have that event on their own calendar.
When a tool returns both a channel id and a channel message id, link the specific message using the channel message mention format. Do not link only the channel unless you are referring to the whole channel.
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 51916df55a..e1c2194012 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -91,7 +91,18 @@ list / delete personal keys; the secret is shown only once and is sent as
`x-macro-user-api-key`), `Notifications`, `Billing`,
`Appearance`, `Mobile App`, `Shortcuts` (interactive keyboard visualization, not a list);
Workspace → `Team`, `Tags`, `CRM`, `Connections` (email/tool OAuth), `MCP server`
-(setup snippets for Claude Code / Codex CLI / Claude.ai / ChatGPT / IDE), `Bots`; `Log out`.
+(setup snippets for Claude Code / Codex CLI / Claude.ai / ChatGPT / IDE), `Agents`, `Bots`;
+`Log out`.
+`Agents` lists team and private agents with `Create agent` / `Edit <name>` dialogs grouped
+Profile, Behavior, Runtime, Connections, Channels, Share. Connections is a radio pair:
+`Use my connected apps` (default; the agent gets whatever the person running it has
+connected) or `Specific apps`, which reveals a `Search connectors` box over the whole
+Pipedream catalog (results are `option` rows; picking one adds it) and a row per picked app
+with a connected / not-connected dot for the *current viewer* plus an inline `Connect`
+that opens the Pipedream Connect flow inside the dialog. Unconnected picks never block
+saving; each teammate connects their own account. An agent session that calls a picked
+but unconnected app gets a tool result saying so, and the agent's reply renders a
+`Connect <app>` chip that opens Settings → Connections for that app.
`Back to app` returns to the previous surface. Open via user-email button menu or `Ctrl+;`.
## Notifications
diff --git a/packages/lexical-core/decoratorRegistry.ts b/packages/lexical-core/decoratorRegistry.ts
index 77fedc44d1..c333ffd549 100644
--- a/packages/lexical-core/decoratorRegistry.ts
+++ b/packages/lexical-core/decoratorRegistry.ts
@@ -4,6 +4,10 @@ import type {
AgentContextNode,
} from './nodes/AgentContextNode';
import type { AwaitDecoratorProps, AwaitNode } from './nodes/AwaitNode';
+import type {
+ ConnectAppDecoratorProps,
+ ConnectAppNode,
+} from './nodes/ConnectAppNode';
import type {
ContactMentionDecoratorProps,
ContactMentionNode,
@@ -163,6 +167,10 @@ export interface NodeDecoratorMap {
klass: typeof TagMentionNode;
props: TagMentionDecoratorProps;
};
+ ConnectAppNode: {
+ klass: typeof ConnectAppNode;
+ props: ConnectAppDecoratorProps;
+ };
WatermarkNode: {
klass: typeof WatermarkNode;
props: WatermarkDecoratorProps;
diff --git a/packages/lexical-core/index.ts b/packages/lexical-core/index.ts
index 9d24200dbc..4970d425cb 100644
--- a/packages/lexical-core/index.ts
+++ b/packages/lexical-core/index.ts
@@ -7,6 +7,7 @@ export * from './nodes/AwaitNode';
export * from './nodes/ClassedBlockNode';
export * from './nodes/CommentNode';
export * from './nodes/CompletionNode';
+export * from './nodes/ConnectAppNode';
export * from './nodes/ContactMentionNode';
export * from './nodes/CustomCodeNode';
export * from './nodes/DateMentionNode';
diff --git a/packages/lexical-core/node-list.ts b/packages/lexical-core/node-list.ts
index b76654c798..59e0191fca 100644
--- a/packages/lexical-core/node-list.ts
+++ b/packages/lexical-core/node-list.ts
@@ -18,6 +18,7 @@ import { AwaitNode } from './nodes/AwaitNode';
import { ClassedBlockNode } from './nodes/ClassedBlockNode';
import { CommentNode } from './nodes/CommentNode';
import { CompletionNode } from './nodes/CompletionNode';
+import { ConnectAppNode } from './nodes/ConnectAppNode';
import { ContactMentionNode } from './nodes/ContactMentionNode';
import { CustomCodeNode } from './nodes/CustomCodeNode';
import { DateMentionNode } from './nodes/DateMentionNode';
@@ -110,6 +111,7 @@ export const SupportedNodeTypes = [
WatermarkNode,
ThemeMentionNode,
TagMentionNode,
+ ConnectAppNode,
UnknownMentionNode,
AwaitNode,
MagicChipNode,
diff --git a/packages/lexical-core/nodes/ConnectAppNode.ts b/packages/lexical-core/nodes/ConnectAppNode.ts
new file mode 100644
index 0000000000..78f6ca6f85
--- /dev/null
+++ b/packages/lexical-core/nodes/ConnectAppNode.ts
@@ -0,0 +1,163 @@
+import {
+ $applyNodeReplacement,
+ DecoratorNode,
+ type DOMConversionMap,
+ type EditorConfig,
+ type EditorThemeClasses,
+ type LexicalEditor,
+ type LexicalNode,
+ type NodeKey,
+ type SerializedLexicalNode,
+ type Spread,
+} from 'lexical';
+import { type DecoratorComponent, getDecorator } from '../decoratorRegistry';
+import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';
+
+const VERSION = 1;
+
+/**
+ * The tag an agent emits when a tool call failed because the person running
+ * the session has not connected an app. Mirrors the egress proxy's
+ * `CONNECT_APP_TAG`; the payload shape is `{"appSlug": ..., "name": ...}`.
+ */
+export const CONNECT_APP_TAG = 'm-connect-app';
+
+export type ConnectAppInfo = {
+ /** Pipedream app slug, e.g. `linear`. */
+ appSlug: string;
+ /** Display name, e.g. `Linear`. */
+ name: string;
+};
+
+export type SerializedConnectAppNode = Spread<
+ ConnectAppInfo,
+ SerializedLexicalNode
+>;
+
+export type ConnectAppDecoratorProps = ConnectAppInfo & {
+ key: NodeKey;
+ theme: EditorThemeClasses;
+};
+
+/** Only slugs the egress proxy would route: lowercase ascii, digits, `-`, `_`. */
+export function isConnectAppSlug(value: unknown): value is string {
+ return typeof value === 'string' && /^[a-z0-9_-]+$/.test(value);
+}
+
+/**
+ * An inline chip offering to connect one Pipedream app. Rendered from a reply
+ * the agent wrote after the egress proxy told it the app was not connected
+ * for the session owner; clicking it takes the reader to Settings →
+ * Connections with that app ready to connect.
+ */
+export class ConnectAppNode extends DecoratorNode<
+ DecoratorComponent<ConnectAppDecoratorProps> | undefined
+> {
+ __appSlug: string;
+ __name: string;
+
+ static getType() {
+ return 'connect-app';
+ }
+
+ isInline(): boolean {
+ return true;
+ }
+
+ isKeyboardSelectable(): boolean {
+ return true;
+ }
+
+ static clone(node: ConnectAppNode) {
+ return new ConnectAppNode(node.__appSlug, node.__name, node.__key);
+ }
+
+ constructor(appSlug: string, name: string, key?: NodeKey) {
+ super(key);
+ this.__appSlug = appSlug;
+ this.__name = name;
+ }
+
+ static importJSON(serializedNode: SerializedConnectAppNode) {
+ const node = $createConnectAppNode(
+ serializedNode.appSlug,
+ serializedNode.name
+ );
+ $applyIdFromSerialized(node, serializedNode);
+ return node;
+ }
+
+ exportJSON(): SerializedConnectAppNode {
+ return {
+ ...super.exportJSON(),
+ appSlug: this.__appSlug,
+ name: this.__name,
+ type: ConnectAppNode.getType(),
+ version: VERSION,
+ };
+ }
+
+ exportComponentProps(): ConnectAppInfo {
+ return { appSlug: this.__appSlug, name: this.__name };
+ }
+
+ createDOM(_config: EditorConfig): HTMLElement {
+ const span = document.createElement('span');
+ span.setAttribute('data-connect-app', this.__appSlug);
+ return span;
+ }
+
+ updateDOM(_prevNode: ConnectAppNode, _dom: HTMLElement): boolean {
+ return false;
+ }
+
+ /** Nothing pastes one of these; they only arrive through the transformer. */
+ static importDOM(): DOMConversionMap<HTMLElement> | null {
+ return null;
+ }
+
+ exportDOM() {
+ const element = document.createElement('span');
+ element.setAttribute('data-connect-app', this.__appSlug);
+ element.textContent = `Connect ${this.__name}`;
+ return { element };
+ }
+
+ getTextContent(): string {
+ return `Connect ${this.__name}`;
+ }
+
+ getAppSlug(): string {
+ return this.__appSlug;
+ }
+
+ getName(): string {
+ return this.__name;
+ }
+
+ decorate(_: LexicalEditor, config: EditorConfig) {
+ const decorator = getDecorator<ConnectAppDecoratorProps>(ConnectAppNode);
+ if (decorator) {
+ return () =>
+ decorator({
+ appSlug: this.__appSlug,
+ name: this.__name,
+ key: this.getKey(),
+ theme: config.theme,
+ });
+ }
+ }
+}
+
+export function $createConnectAppNode(
+ appSlug: string,
+ name: string
+): ConnectAppNode {
+ return $applyNodeReplacement(new ConnectAppNode(appSlug, name));
+}
+
+export function $isConnectAppNode(
+ node: ConnectAppNode | LexicalNode | null | undefined
+): node is ConnectAppNode {
+ return node instanceof ConnectAppNode;
+}
diff --git a/packages/lexical-core/tests/connect-app.test.ts b/packages/lexical-core/tests/connect-app.test.ts
new file mode 100644
index 0000000000..9fb86d6a53
--- /dev/null
+++ b/packages/lexical-core/tests/connect-app.test.ts
@@ -0,0 +1,94 @@
+import {
+ $convertFromMarkdownString,
+ $convertToMarkdownString,
+} from '@lexical/markdown';
+import { $getRoot, $isParagraphNode, createEditor } from 'lexical';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import { SupportedNodeTypes } from '../node-list';
+import { $isConnectAppNode, ConnectAppNode } from '../nodes/ConnectAppNode';
+import { $isUnknownMentionNode } from '../nodes/UnknownMentionNode';
+import { ALL_TRANSFORMERS, EXTERNAL_TRANSFORMERS } from '../transformers';
+import { markdownToEmbeddingText, markdownToPlainText } from '../utils/parsers';
+
+const TAG =
+ '<m-connect-app>{"appSlug":"linear","name":"Linear"}</m-connect-app>';
+
+function editorWith(markdown: string, transformers = ALL_TRANSFORMERS) {
+ const editor = createEditor({
+ nodes: SupportedNodeTypes,
+ onError: (error) => {
+ throw error;
+ },
+ });
+ editor.update(
+ () => {
+ $convertFromMarkdownString(markdown, transformers);
+ },
+ { discrete: true }
+ );
+ return editor;
+}
+
+function inlineNodes(editor: ReturnType<typeof createEditor>) {
+ return editor.getEditorState().read(() => {
+ const [paragraph] = $getRoot().getChildren();
+ if (!$isParagraphNode(paragraph)) throw new Error('expected a paragraph');
+ return paragraph.getChildren();
+ });
+}
+
+describe('connect-app chip', () => {
+ let consoleError: ReturnType<typeof vi.spyOn>;
+ beforeAll(() => {
+ consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+ afterAll(() => {
+ consoleError.mockRestore();
+ });
+
+ it('parses the tag an agent copies out of a tool result', () => {
+ const editor = editorWith(
+ `Please connect it first: ${TAG} then ask again.`
+ );
+ const chip = inlineNodes(editor).find($isConnectAppNode);
+ expect(chip).toBeInstanceOf(ConnectAppNode);
+ expect(chip?.getAppSlug()).toBe('linear');
+ expect(chip?.getName()).toBe('Linear');
+ });
+
+ it('renders inside the magic chip, which uses the external transformers', () => {
+ const editor = editorWith(TAG, EXTERNAL_TRANSFORMERS);
+ expect(inlineNodes(editor).some($isConnectAppNode)).toBe(true);
+ });
+
+ it('round-trips through markdown export', () => {
+ const editor = editorWith(TAG);
+ const exported = editor
+ .getEditorState()
+ .read(() => $convertToMarkdownString(ALL_TRANSFORMERS));
+ expect(exported).toContain(TAG);
+ });
+
+ it('falls back to the unknown-mention chip for a slug the proxy would not route', () => {
+ for (const payload of [
+ '{"appSlug":"Linear App","name":"Linear"}',
+ '{"appSlug":"../mcp-macro","name":"x"}',
+ '{"appSlug":"linear"}',
+ 'not json',
+ ]) {
+ const editor = editorWith(`<m-connect-app>${payload}</m-connect-app>`);
+ const nodes = inlineNodes(editor);
+ expect(nodes.some($isConnectAppNode), payload).toBe(false);
+ expect(nodes.some($isUnknownMentionNode), payload).toBe(true);
+ }
+ });
+
+ it('reads as its call to action in plain and embedding text', () => {
+ expect(markdownToPlainText(`Do this: ${TAG}`)).toBe(
+ 'Do this: Connect Linear'
+ );
+ expect(markdownToEmbeddingText(`Do this: ${TAG}`)).toBe(
+ 'Do this: Connect Linear'
+ );
+ });
+});
diff --git a/packages/lexical-core/transformers/index.ts b/packages/lexical-core/transformers/index.ts
index 6eebb3cba1..32d1a04f29 100644
--- a/packages/lexical-core/transformers/index.ts
+++ b/packages/lexical-core/transformers/index.ts
@@ -21,6 +21,7 @@ import {
E_PR_MENTION,
E_TAG_MENTION,
E_USER_MENTION,
+ I_CONNECT_APP,
I_CONTACT_MENTION,
I_DATE_MENTION,
I_DOCUMENT_CARD,
@@ -85,6 +86,7 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [
I_EQUATION_NODE,
I_THEME_MENTION,
I_TAG_MENTION,
+ I_CONNECT_APP,
I_WATERMARK,
...CUSTOM_TRANSFORMERS,
UNKNOWN_MENTION, // Must be last to act as fallback for unrecognized XML tags
@@ -114,6 +116,7 @@ export const EXTERNAL_TRANSFORMERS: Transformer[] = [
E_DATE_MENTION,
E_REPLY_TARGET_NODE,
E_TAG_MENTION,
+ I_CONNECT_APP, // agent replies render in the magic chip through this list
// order matters
E_MULTILINE_BLOCK_EQUATION_NODE,
E_BLOCK_EQUATION_NODE,
@@ -168,6 +171,7 @@ export const ALL_TRANSFORMERS: Transformer[] = [
I_EQUATION_NODE,
I_THEME_MENTION,
I_TAG_MENTION,
+ I_CONNECT_APP,
I_WATERMARK,
E_WATERMARK,
E_TAG_MENTION,
diff --git a/packages/lexical-core/transformers/mentions.ts b/packages/lexical-core/transformers/mentions.ts
index 8b50352a25..b09e904e26 100644
--- a/packages/lexical-core/transformers/mentions.ts
+++ b/packages/lexical-core/transformers/mentions.ts
@@ -3,6 +3,11 @@ import type {
TextMatchTransformer,
} from '@lexical/markdown';
import type { ElementNode, LexicalNode, TextNode } from 'lexical';
+import {
+ CONNECT_APP_TAG,
+ ConnectAppNode,
+ isConnectAppSlug,
+} from '../nodes/ConnectAppNode';
import { ContactMentionNode } from '../nodes/ContactMentionNode';
import { DateMentionNode } from '../nodes/DateMentionNode';
import { DocumentCardNode } from '../nodes/DocumentCardNode';
@@ -489,6 +494,42 @@ export const I_THEME_MENTION: TextMatchTransformer = {
},
};
+// Connect-app chips: an agent's "this app is not connected, here is how"
+// affordance. Same JSON-in-body shape as every other m-* tag.
+export const I_CONNECT_APP: TextMatchTransformer = {
+ dependencies: [ConnectAppNode, UnknownMentionNode],
+ type: 'text-match',
+ regExp: new RegExp(`<${CONNECT_APP_TAG}>(.*?)</${CONNECT_APP_TAG}>`),
+ importRegExp: new RegExp(`<${CONNECT_APP_TAG}>(.*?)</${CONNECT_APP_TAG}>`),
+ export: (node) => {
+ if (!(node instanceof ConnectAppNode)) return null;
+ const data = JSON.stringify({
+ appSlug: node.getAppSlug(),
+ name: node.getName(),
+ });
+ return `<${CONNECT_APP_TAG}>${data}</${CONNECT_APP_TAG}>`;
+ },
+ replace: (node: TextNode, match: RegExpMatchArray) => {
+ try {
+ const parsed: unknown = JSON.parse(match[1]);
+ if (typeof parsed !== 'object' || parsed === null) {
+ throw new Error('Invalid connect-app JSON');
+ }
+ const { appSlug, name } = parsed as Record<string, unknown>;
+ // The slug ends up in a URL and is model-authored: only the charset the
+ // proxy routes on is accepted, anything else falls back to the
+ // unknown-mention chip rather than being repaired.
+ if (!isConnectAppSlug(appSlug) || typeof name !== 'string' || !name) {
+ throw new Error('Invalid connect-app payload');
+ }
+ node.replace(new ConnectAppNode(appSlug, name));
+ } catch (e) {
+ console.error('Error in I_CONNECT_APP replace:', e);
+ replaceTextWithUnknownMention(node, 'Connect app');
+ }
+ },
+};
+
// Internal Tag Mentions
export const I_TAG_MENTION: TextMatchTransformer = {
dependencies: [TagMentionNode, UnknownMentionNode],
diff --git a/packages/lexical-core/utils/parsers.ts b/packages/lexical-core/utils/parsers.ts
index dbd33fd2b9..ae581f725f 100644
--- a/packages/lexical-core/utils/parsers.ts
+++ b/packages/lexical-core/utils/parsers.ts
@@ -70,6 +70,20 @@ export function parsePullRequestMentions(text: string): string {
});
}
+/** `<m-connect-app>` chips read as their call to action. */
+export function parseConnectApps(text: string): string {
+ return text.replace(/<m-connect-app>(.*?)<\/m-connect-app>/g, (_, json) => {
+ try {
+ const data = JSON.parse(json);
+ return typeof data.name === 'string' && data.name
+ ? `Connect ${data.name}`
+ : '';
+ } catch {
+ return '';
+ }
+ });
+}
+
export function parseTagMentions(text: string): string {
return text.replace(/<m-tag>(.*?)<\/m-tag>/g, (_, json) => {
try {
@@ -194,6 +208,7 @@ export function markdownToPlainText(markdown: string): string {
parseDocumentMentions,
parsePullRequestMentions,
parseTagMentions,
+ parseConnectApps,
parseSnapshots,
parseDocumentCards,
parseLinks,
@@ -382,6 +397,9 @@ export function markdownToEmbeddingText(markdown: string): string {
data.name ? `#${data.name}` : ''
);
text = replaceJsonTag(text, 'm-theme-mention', (data) => data.name || '');
+ text = replaceJsonTag(text, 'm-connect-app', (data) =>
+ data.name ? `Connect ${data.name}` : ''
+ );
text = replaceJsonTag(text, 'm-await', (data) => data.text || '');
text = replaceJsonTag(
text,
diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.ts
index ba1206b282..dabfa05e20 100644
--- a/packages/sdk/generated/storage/index.ts
+++ b/packages/sdk/generated/storage/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentChannelScope, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreatePairingRequest, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, RequestedHarnessScope, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
+export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentChannelScope, AgentMcpServer, AgentMcpServers, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreatePairingRequest, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, RequestedHarnessScope, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 956e0b2673..6f819730a9 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -115,6 +115,10 @@ export type Agent = {
* Instructions supplied to the agent at the start of a conversation.
*/
instructions: string;
+ /**
+ * Which MCP servers sessions of this agent are handed.
+ */
+ mcp: AgentMcpServers;
};
/**
@@ -122,6 +126,40 @@ export type Agent = {
*/
export type AgentChannelScope = 'all' | 'selected';
+/**
+ * One Pipedream app an agent lists under [`AgentMcpServers::Selected`].
+ *
+ * Only the catalog identity is stored. Whether a given person has connected
+ * the app is theirs, resolved at call time by the egress proxy, never here.
+ */
+export type AgentMcpServer = {
+ /**
+ * Pipedream app slug, e.g. `linear`.
+ */
+ app_slug: string;
+ /**
+ * Display name, e.g. `Linear`.
+ */
+ server_name: string;
+};
+
+/**
+ * Which Pipedream MCP servers an agent's sessions are handed.
+ *
+ * One value for the whole choice, so a selection can never travel without
+ * its scope or a scope without its selection. Serialized with a `scope` tag,
+ * which the generated TypeScript sees as a discriminated union.
+ */
+export type AgentMcpServers = {
+ scope: 'owner_connections';
+} | {
+ scope: 'selected';
+ /**
+ * The apps, in the order the agent's author picked them.
+ */
+ servers: Array<AgentMcpServer>;
+};
+
export type Anchor = PdfAnchor;
export type AnchorId = PdfAnchorId & {
@@ -2785,6 +2823,10 @@ export type CreateAgentRequest = {
* Instructions supplied to the agent at the start of a conversation.
*/
instructions: string;
+ /**
+ * Which MCP servers sessions of this agent are handed.
+ */
+ mcp?: AgentMcpServers;
/**
* Display name.
*/
@@ -8670,6 +8712,10 @@ export type UpdateAgentRequest = {
* Instructions supplied to the agent at the start of a conversation.
*/
instructions: string;
+ /**
+ * Which MCP servers sessions of this agent are handed.
+ */
+ mcp?: AgentMcpServers;
/**
* Display name.
*/
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 9fe7d858e8..3f64f2a747 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -12656,7 +12656,8 @@
"harness",
"default_model",
"channel_scope",
- "channel_ids"
+ "channel_ids",
+ "mcp"
],
"properties": {
"bot": {
@@ -12697,6 +12698,10 @@
"instructions": {
"type": "string",
"description": "Instructions supplied to the agent at the start of a conversation."
+ },
+ "mcp": {
+ "$ref": "#/components/schemas/AgentMcpServers",
+ "description": "Which MCP servers sessions of this agent are handed."
}
}
},
@@ -12705,6 +12710,55 @@
"description": "Whether an agent is available everywhere or only in selected channels.",
"enum": ["all", "selected"]
},
+ "AgentMcpServer": {
+ "type": "object",
+ "description": "One Pipedream app an agent lists under [`AgentMcpServers::Selected`].\n\nOnly the catalog identity is stored. Whether a given person has connected\nthe app is theirs, resolved at call time by the egress proxy, never here.",
+ "required": ["app_slug", "server_name"],
+ "properties": {
+ "app_slug": {
+ "type": "string",
+ "description": "Pipedream app slug, e.g. `linear`."
+ },
+ "server_name": {
+ "type": "string",
+ "description": "Display name, e.g. `Linear`."
+ }
+ }
+ },
+ "AgentMcpServers": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "Whatever apps the person running the session has connected.",
+ "required": ["scope"],
+ "properties": {
+ "scope": {
+ "type": "string",
+ "enum": ["owner_connections"]
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "Exactly these apps, connected or not.",
+ "required": ["servers", "scope"],
+ "properties": {
+ "scope": {
+ "type": "string",
+ "enum": ["selected"]
+ },
+ "servers": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AgentMcpServer"
+ },
+ "description": "The apps, in the order the agent's author picked them."
+ }
+ }
+ }
+ ],
+ "description": "Which Pipedream MCP servers an agent's sessions are handed.\n\nOne value for the whole choice, so a selection can never travel without\nits scope or a scope without its selection. Serialized with a `scope` tag,\nwhich the generated TypeScript sees as a discriminated union."
+ },
"Anchor": {
"oneOf": [
{
@@ -16552,6 +16606,10 @@
"type": "string",
"description": "Instructions supplied to the agent at the start of a conversation."
},
+ "mcp": {
+ "$ref": "#/components/schemas/AgentMcpServers",
+ "description": "Which MCP servers sessions of this agent are handed."
+ },
"name": {
"type": "string",
"description": "Display name."
@@ -26242,6 +26300,10 @@
"type": "string",
"description": "Instructions supplied to the agent at the start of a conversation."
},
+ "mcp": {
+ "$ref": "#/components/schemas/AgentMcpServers",
+ "description": "Which MCP servers sessions of this agent are handed."
+ },
"name": {
"type": "string",
"description": "Display name."
diff --git a/services/agent_harness_service/src/agent_runtime_directory.rs b/services/agent_harness_service/src/agent_runtime_directory.rs
index 15cba14031..08fec856af 100644
--- a/services/agent_harness_service/src/agent_runtime_directory.rs
+++ b/services/agent_harness_service/src/agent_runtime_directory.rs
@@ -39,6 +39,7 @@ impl AgentRuntimeDirectory for PgAgentRuntimeDirectory {
model: agent.default_model,
harness: agent.harness,
instructions: agent.instructions,
+ mcp_servers: agent.mcp,
}))
}
}
diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rs
index 4b256831c1..59dde380b2 100644
--- a/services/agent_harness_service/src/api.rs
+++ b/services/agent_harness_service/src/api.rs
@@ -52,14 +52,14 @@ fn health_router(ready: tokio::sync::watch::Receiver<bool>) -> Router {
/// No CORS layer and no Swagger: nothing browses this. Its only client is a
/// sandbox, and its only credential is a session token.
pub async fn serve_egress<Service>(
- service: Service,
+ service: std::sync::Arc<Service>,
port: u16,
shutdown: impl Future<Output = ()> + Send + 'static,
) -> anyhow::Result<()>
where
Service: EgressService + 'static,
{
- let app = egress_router(EgressRouterState::new(std::sync::Arc::new(service)));
+ let app = egress_router(EgressRouterState::new(service));
let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{port}"))
.await
diff --git a/services/agent_harness_service/src/containers.rs b/services/agent_harness_service/src/containers.rs
index 40f5e0f1b4..95a884def6 100644
--- a/services/agent_harness_service/src/containers.rs
+++ b/services/agent_harness_service/src/containers.rs
@@ -152,7 +152,10 @@ where
async fn spawn(&self, command: SpawnContainer) -> Result<Self::Transport> {
match self.route(command.session_id).await? {
Route::InMem(facts) => Ok(RoutedTransport::InMem(
- self.inmem().manager.attach(facts).await,
+ self.inmem()
+ .manager
+ .attach(facts, Some(command.egress.session_token))
+ .await,
)),
Route::Sandbox => self
.sandbox
@@ -182,7 +185,7 @@ where
async fn resume(&self, session: AgentSessionId) -> Result<Self::Transport> {
match self.route(session).await? {
Route::InMem(facts) => Ok(RoutedTransport::InMem(
- self.inmem().manager.attach(facts).await,
+ self.inmem().manager.attach(facts, None).await,
)),
Route::Sandbox => self
.sandbox
@@ -192,11 +195,13 @@ where
}
}
- /// An in-process session has no container and no egress environment, so
- /// there is no token to read back; sandboxes delegate to their provider.
+ /// An in-process session has no container environment to read a token
+ /// back from, so the manager remembers the one spawn handed it; a
+ /// session this process never spawned yields none. Sandboxes delegate to
+ /// their provider.
async fn session_token(&self, session: AgentSessionId) -> Result<Option<String>> {
match self.route(session).await? {
- Route::InMem(_) => Ok(None),
+ Route::InMem(_) => Ok(self.inmem().manager.session_token(session)),
Route::Sandbox => self.sandbox.session_token(session).await,
}
}
diff --git a/services/agent_harness_service/src/containers/test.rs b/services/agent_harness_service/src/containers/test.rs
index a808f420f4..9474bfd9ce 100644
--- a/services/agent_harness_service/src/containers/test.rs
+++ b/services/agent_harness_service/src/containers/test.rs
@@ -96,3 +96,14 @@ async fn routes_an_owned_bot_to_the_sandbox() {
Route::Sandbox
));
}
+
+/// The in-process runtime skips Macro's own server by the name the harness
+/// gives it, and restates that name rather than importing it. This is the one
+/// crate that sees both, so it is where they are held equal.
+#[test]
+fn the_in_process_runtime_and_the_harness_agree_on_macros_server_name() {
+ assert_eq!(
+ agent_inmem::domain::mcp::MACRO_MCP_NAME,
+ agent_harness::domain::model::MACRO_MCP_NAME
+ );
+}
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 228ee3312d..31e9cc9766 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -48,11 +48,13 @@ use agent_harness::outbound::forward::RedisCommandForwarder;
use agent_harness::outbound::local::{LocalContainerManager, LocalSettings};
use agent_harness::outbound::routing::RoutedContainerManager;
use agent_harness::outbound::runtime_registry::{HarnessKeyedConnections, RuntimeRegistry};
+use agent_inmem::outbound::acp_mcp::AcpMcpConnector;
+use agent_inmem::outbound::egress_mcp::EgressMcpClient;
use agent_inmem::outbound::log_frames::LogFrameSource;
use agent_inmem::outbound::manager::InMemAgentManager;
use agent_inmem::outbound::rig_engine::RigTurnEngine;
use agent_runtime_directory::PgAgentRuntimeDirectory;
-use agent_session::domain::model::ReplicaId;
+use agent_session::domain::model::{AgentMcpServers, ReplicaId};
use agent_session::domain::ports::{NoOpRealtime, SessionOwnership as _};
use agent_session::domain::service::AgentSessionServiceImpl;
use agent_session::inbound::axum_router::{
@@ -265,6 +267,62 @@ async fn run() -> anyhow::Result<()> {
// Tracks event publishes the in-memory agent's tool context starts;
// closed and drained on shutdown so nothing is dropped mid-publish.
let event_broker_tracker = tokio_util::task::TaskTracker::new();
+ // MCP connections: the same rows the chat tool path reads, so an app
+ // connected in Macro is an app the sandbox can reach, with nothing to
+ // keep in sync. The rows hold no secrets - Pipedream owns the grants.
+ let mcp_connections = Arc::new(PgConnectionRepo::new(pool.clone()));
+
+ // The client that addresses Pipedream's remote MCP server, built from the
+ // same credentials `document_cognition_service` uses.
+ let pipedream = PipedreamClient::new(PipedreamConfig {
+ client_id: config.pipedream_client_id.to_string(),
+ client_secret: config.pipedream_client_secret.to_string(),
+ project_id: config.pipedream_project_id.to_string(),
+ environment: config.pipedream_environment.clone(),
+ api_url: config.pipedream_api_url.clone(),
+ mcp_url: config.pipedream_mcp_url.clone(),
+ // Only Connect tokens carry allowed origins, and this service never
+ // mints one: connecting apps stays in the app.
+ allowed_origins: Vec::new(),
+ })
+ .context("failed to build Pipedream client")?;
+
+ // Every session's MCP servers: Macro's own under the reserved `macro`
+ // slug, then the owner's Pipedream connections. The `macro` credential is
+ // signed inline with the same key authentication_service holds; what this
+ // process hands out is always single-user and minutes from expiry.
+ let mcp_credentials = WithMacroMcp::new(
+ PipedreamMcpCredentials::new(Arc::clone(&mcp_connections), pipedream),
+ MacroApiTokenSigner::new(
+ pool.clone(),
+ config.macro_api_token_issuer.as_ref(),
+ config.macro_api_token_private_secret_key.as_ref(),
+ ),
+ url::Url::parse(&config.macro_mcp_url).context("MACRO_MCP_URL is not a url")?,
+ // The one gate on cleartext: a local stack's mcp-service is dialed
+ // across the compose bridge, where TLS would be theater. Everywhere
+ // else, an http URL refuses to boot.
+ matches!(config.environment, Environment::Local),
+ )
+ .context("the macro MCP upstream is misconfigured")?;
+
+ // The egress proxy: one binary today, its own listener from the start.
+ // Shared with the in-memory runtime, which calls it directly rather than
+ // through that listener.
+ let egress = Arc::new(EgressServiceImpl::new(
+ StoredTokenSessionAuthority::new(PgAgentSessionRepo::new(pool.clone())),
+ mcp_credentials,
+ GithubAppTokens::new(InstallationTokenService::new(
+ InstallationTokenConfig {
+ client_id: config.github_sync_app_client_id.clone(),
+ private_key_pem: config.github_sync_app_pem_secret_key.as_ref().to_owned(),
+ },
+ PgGithubSyncRepo::new(pool.clone()),
+ GithubSyncClientImpl::default(),
+ )),
+ ReqwestForwarder::new()?,
+ ));
+
let inmem = match inmem_bot {
Some(_) => {
let tool_context = ai_tools::build_tool_service_context_from_env(
@@ -278,7 +336,13 @@ async fn run() -> anyhow::Result<()> {
// their model context from the same log every frame lands in.
let frames = Arc::new(LogFrameSource::new(session_repo.clone()));
Some(InMemRuntime {
- manager: InMemAgentManager::new(engine, frames),
+ manager: InMemAgentManager::new(
+ engine,
+ frames,
+ Arc::new(AcpMcpConnector::new(EgressMcpClient::new(Arc::clone(
+ &egress,
+ )))),
+ ),
})
}
None => None,
@@ -321,6 +385,7 @@ async fn run() -> anyhow::Result<()> {
model: config.harness_model.clone(),
harness: config.harness_slug.clone(),
instructions: String::new(),
+ mcp_servers: AgentMcpServers::OwnerConnections,
},
)];
if let Some(inmem_bot) = inmem_bot {
@@ -331,6 +396,7 @@ async fn run() -> anyhow::Result<()> {
model: config.inmem_model.clone(),
harness: config.inmem_harness_slug.clone(),
instructions: String::new(),
+ mcp_servers: AgentMcpServers::OwnerConnections,
},
));
}
@@ -341,6 +407,7 @@ async fn run() -> anyhow::Result<()> {
model: config.harness_model.clone(),
harness: "cursor".to_owned(),
instructions: String::new(),
+ mcp_servers: AgentMcpServers::OwnerConnections,
},
));
let runtime_directory =
@@ -432,26 +499,6 @@ async fn run() -> anyhow::Result<()> {
.with_managed_bot(bot);
}
- // MCP connections: the same rows the chat tool path reads, so an app
- // connected in Macro is an app the sandbox can reach, with nothing to
- // keep in sync. The rows hold no secrets - Pipedream owns the grants.
- let mcp_connections = Arc::new(PgConnectionRepo::new(pool.clone()));
-
- // The client that addresses Pipedream's remote MCP server, built from the
- // same credentials `document_cognition_service` uses.
- let pipedream = PipedreamClient::new(PipedreamConfig {
- client_id: config.pipedream_client_id.to_string(),
- client_secret: config.pipedream_client_secret.to_string(),
- project_id: config.pipedream_project_id.to_string(),
- environment: config.pipedream_environment.clone(),
- api_url: config.pipedream_api_url.clone(),
- mcp_url: config.pipedream_mcp_url.clone(),
- // Only Connect tokens carry allowed origins, and this service never
- // mints one: connecting apps stays in the app.
- allowed_origins: Vec::new(),
- })
- .context("failed to build Pipedream client")?;
-
let harness = Arc::new(AgentHarnessService::new(
sessions,
containers,
@@ -593,39 +640,6 @@ async fn run() -> anyhow::Result<()> {
config.internal_api_key.clone(),
));
- // Every session's MCP servers: Macro's own under the reserved `macro`
- // slug, then the owner's Pipedream connections. The `macro` credential is
- // signed inline with the same key authentication_service holds; what this
- // process hands out is always single-user and minutes from expiry.
- let mcp_credentials = WithMacroMcp::new(
- PipedreamMcpCredentials::new(mcp_connections, pipedream),
- MacroApiTokenSigner::new(
- pool.clone(),
- config.macro_api_token_issuer.as_ref(),
- config.macro_api_token_private_secret_key.as_ref(),
- ),
- url::Url::parse(&config.macro_mcp_url).context("MACRO_MCP_URL is not a url")?,
- // The one gate on cleartext: a local stack's mcp-service is dialed
- // across the compose bridge, where TLS would be theater. Everywhere
- // else, an http URL refuses to boot.
- matches!(config.environment, Environment::Local),
- )
- .context("the macro MCP upstream is misconfigured")?;
-
- // The egress proxy: one binary today, its own listener from the start.
- let egress = EgressServiceImpl::new(
- StoredTokenSessionAuthority::new(PgAgentSessionRepo::new(pool.clone())),
- mcp_credentials,
- GithubAppTokens::new(InstallationTokenService::new(
- InstallationTokenConfig {
- client_id: config.github_sync_app_client_id.clone(),
- private_key_pem: config.github_sync_app_pem_secret_key.as_ref().to_owned(),
- },
- PgGithubSyncRepo::new(pool.clone()),
- GithubSyncClientImpl::default(),
- )),
- ReqwestForwarder::new()?,
- );
let egress_port = config.egress_port;
let egress_http = tokio::spawn(async move {
if let Err(error) = api::serve_egress(egress, egress_port, shutdown_signal()).await {
diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rs
index 3e5d87c260..d776c1afd3 100644
--- a/services/document_storage_service/src/api/swagger.rs
+++ b/services/document_storage_service/src/api/swagger.rs
@@ -597,6 +597,8 @@ use utoipa::OpenApi;
// Bots
bots::domain::models::Agent,
bots::domain::models::AgentChannelScope,
+ bots::domain::models::AgentMcpServers,
+ bots::domain::models::AgentMcpServer,
bots::domain::models::CreateAgentRequest,
bots::domain::models::UpdateAgentRequest,
bots::domain::models::Bot,