Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(connectors): the Custom Connector node gives an agent a connector's tools
trohitg323293bbe0b6
diff --git a/CLAUDE.md b/CLAUDE.mdindex d24b2bc3..171be396 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -33,7 +33,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Email Service](./docs-internal/email_service.md)** | IMAP/SMTP integration via Himalaya CLI with EmailService orchestrator, provider presets, custom credential fallback, and polling triggers || **[Browser](./docs-internal/browser.md)** | Current `browser` node: installed Chrome/Edge/Chromium in a dedicated profile rendered inside the workspace by default (`BROWSER_RUNTIME=system`, `BROWSER_HEADLESS=true`) and pinned browser-use CLI. Chrome for Testing requires explicit `BROWSER_RUNTIME=testing`. System mode retains the native user agent and OS password-store/keychain integration; basic/mock keychain flags are restricted to testing mode. Includes persistent employee/shared profiles (the Credentials / Connectors "Web browser" panel adds, deletes and imports logins from a session file; the node's profile dropdown lists only the caller's profiles, via `current_load_options_principal()`), session leases, agent/user handoff, network policy, screenshots as workspace FileRefs and authenticated `/ws/browser` live viewing. Plugin-owned installation is lazy (`_install_chrome.py`, `_install_bu.py`); importing or shutting down the plugin never installs it. Replaces the former agent-browser and separate `browserHarness` implementations. || **[Browser Workspace](./docs-internal/browser_workspace.md)** | Home and Dev share `WorkspaceTabs` and `BrowserWorkspace`: Browser / Canvas / Mobile, capability-based discovery, binary JPEG frames, bounded frame credit and decoding, Take control / Hand back, the agent's cursor (`agent_action`: where each click, hover, type or select happened, beside the agent's result and never during a protected login), visibility cleanup and payload-free opt-in diagnostics. The Browser node's parameter panel shows the same viewer, and the Dev dock opens on its Browser tab when an agent in the open workflow asks for help (`browser_updated`). Mobile shows the managed local Android phone. |-| **[MCP Connectors](./docs-internal/mcp_connectors.md)** | Custom connectors: the owner adds an outside MCP server from Connectors → Add (URL, name, sign-in: none, bearer or one header), and OpenCompany is its MCP *client* (`server/nodes/mcp/`, official `mcp` SDK; unrelated to the CLI agents' `/mcp/ide` server). The server reads the tools before keeping anything: streamable HTTP, then SSE; our own httpx client with redirects off; host and resolved addresses checked against `services/netpolicy.py` (shared with the Browser node: never cloud metadata or OpenCompany's own ports, plain http only on the owner's network), within `DISCOVER_S` (45 s, under the app's 60 s probe wait). Kept as `mcp:<slug>` (sign-in, encrypted; plain `model_params._mcp`: tools as accepted, per-tool `{enabled, ask}`, a waiting refresh) and `mcp:<slug>_proxy` (URL). A tool no model could call is kept with the reason, never renamed. Each connector is its own card through the generic `Credential.catalogue_entries` hook and the `_mcp_connector` template. Commands `mcp_connector_add` / `_test` / `_refresh` / `_review` / `_set_tool` / `_remove`; Refresh holds every change for Accept. Client: `AddConnectorForm.tsx` and `panels/McpConnectorPanel.tsx`. |+| **[MCP Connectors](./docs-internal/mcp_connectors.md)** | Custom connectors: the owner adds an outside MCP server from Connectors → Add (URL, name, sign-in: none, bearer or one header), and OpenCompany is its MCP *client* (`server/nodes/mcp/`, official `mcp` SDK; unrelated to the CLI agents' `/mcp/ide` server). The server reads the tools before keeping anything: streamable HTTP, then SSE; our own httpx client with redirects off; host and resolved addresses checked against `services/netpolicy.py` (shared with the Browser node: never cloud metadata or OpenCompany's own ports, plain http only on the owner's network), within `DISCOVER_S` (45 s, under the app's 60 s probe wait). Kept as `mcp:<slug>` (sign-in, encrypted; plain `model_params._mcp`: tools as accepted, per-tool `{enabled, ask}`, a waiting refresh) and `mcp:<slug>_proxy` (URL). A tool no model could call is kept with the reason, never renamed. Each connector is its own card through the generic `Credential.catalogue_entries` hook and the `_mcp_connector` template. Commands `mcp_connector_add` / `_test` / `_refresh` / `_review` / `_set_tool` / `_remove`; Refresh holds every change for Accept. Client: `AddConnectorForm.tsx` and `panels/McpConnectorPanel.tsx`. The `mcpConnector` node on an agent's Tools gives one tool per tool that is on (`ToolNode.tool_bindings`, named `<slug>__<tool>`, run with its binding's locked `mcp_tool` / `mcp_ask` / labels; arguments checked with jsonschema; Ask first per tool through the node's `approval` spec); CLI agents leave it out and RLM refuses it. || **[WhatsApp Business Service](./docs-internal/whatsapp_business_service.md)** | Official Meta Cloud API plugin in [`server/nodes/whatsapp_business/`](./server/nodes/whatsapp_business/) — **distinct from `nodes/whatsapp/`**, which is a personal account over an unofficial Go bridge; they share no node type, credential or palette group. Four nodes: `whatsappBusinessSend` (10 ops — Meta models message type as a *field* on one `/messages` endpoint, so text / media / template / interactive are operations, not nodes), `whatsappBusinessMedia` (the one genuinely separate endpoint family), and the `Receive` / `Status` triggers (kept separate because a canary trigger registers exactly one CloudEvents type). `phone_number_id` is deliberately **absent from Params** and comes from the credential only, because it selects the sending identity — `server_controlled_fields` would keep a model-set value out on every tool path, but an ActionNode's tool schema is its whole `Params` (`ToolInput` is ToolNode-only), so a declared field would still appear in the schema the model sees. Webhook via `register_webhook_source` on the shared catch-all, `X-Hub-Signature-256` HMAC failing closed, composite `wamid:status` dedup ids so `sent→delivered→read` don't collapse. || **[Stripe Service](./docs-internal/stripe_service.md)** | Stripe CLI integration — `stripeAction` (CLI pass-through) + `stripeReceive` (signed-webhook trigger, on a canvas Run and deployed: every Stripe event travels under one CloudEvents type, `com.opencompany.stripe.event.received`, with the Stripe type in `subject` and `data.event_type`, where the node's own `build_filter` reads it; the source shapes the payload once, wakes the in-process waiter through `WebhookSource.handle` and reaches deployed listeners through `dispatch.emit`; deploying starts `stripe listen` through the generic `TriggerNode.prepare_deployment` hook, at Start and at the boot re-arm). Reference plugin for the Wave 12 event framework AND the **CLI-managed-auth pattern**: browser OAuth via `stripe login --non-interactive` + `--complete <url>` (URL extracted from `next_step` shell command via `shlex.split`) + auto-installed binary (`ensure_stripe_cli` from GitHub releases) + marker-token reuse of `auth_service.store_oauth_tokens` + CloudEvents-shaped `broadcast_credential_event("credential.oauth.connected" \| ".disconnected", provider=...)` — zero per-provider hardcoding in the frontend. Daemon stdout/stderr ingested via `ProcessService`'s `line_handler` callback (no log-file tailing); credential gate routed through `await self.has_credential()` so non-api-key auth (`is_logged_in()`) plugs in via subclass override. || **[Vercel Service](./docs-internal/vercel_service.md)** | Vercel CLI integration — `vercelAction` (deploy / inspect / list + `custom` CLI passthrough; AI tool `vercel`). Second reference for the CLI-managed-auth pattern: the **device-flow variant** (`vercel login` is one blocking process — no two-step `--complete`; direct `create_subprocess_exec` + chunk-based banner read for the code-embedding URL, pumps drain pipes for the process lifetime, success gate = auth.json mtime advance + sniff). Dual auth: optional `vercel_token` field (injected as `VERCEL_TOKEN` env, never argv) OR CLI login with marker tokens. All invocations pin `--global-config <DATA_DIR>/vercel/` (the `CLAUDE_CONFIG_DIR` isolation idiom). `bun add` into the shared packages tree (pinned version, via `core/js_runtime.add_package`; the CLI runs on bun). First-deploy project guard raises `NodeUserError` instead of letting Vercel derive an invalid name from the workspace dir. Shipped with the generic OAuthConnect change: Login gates on **required** fields only, so optional fields never block CLI login. |diff --git a/docs-internal/mcp_connectors.md b/docs-internal/mcp_connectors.mdindex eb79a151..d0e29e54 100644--- a/docs-internal/mcp_connectors.md+++ b/docs-internal/mcp_connectors.md@@ -16,6 +16,7 @@ thing: see [CLI Agent Framework](./cli_agent_framework.md).| What is kept (two credential rows) | `server/nodes/mcp/_store.py` || One catalogue card per connector | `server/nodes/mcp/_credentials.py` || The Connectors page's commands | `server/nodes/mcp/_handlers.py` |+| The node that gives an agent the tools | `server/nodes/mcp/mcp_connector.py` || The outbound address rules, shared with the Browser node | `server/services/netpolicy.py` || The cards' shared fields, and the `custom` categories | `server/config/credential_providers.json` (`_mcp_connector`) || The Add form | `client/src/components/credentials/AddConnectorForm.tsx` |@@ -51,8 +52,10 @@ is kept.(`CREDENTIAL_PROBE_REQUEST_TIMEOUT`), so a slow read never finishes afterthe app gave up on it.- **Its name**: the slug comes from the name, or else from the host- (python-slugify, at most 20 characters). A second connector needs its own- name.+ (python-slugify, at most 20 characters). It starts with a letter+ (`mcp-` goes in front otherwise), because its tools' names start with it+ and some models (Gemini) take only a name that starts with a letter. A+ second connector needs its own name.## What is kept@@ -122,6 +125,33 @@ them with `mcp_connector_review`. Until then, the tools the owner acceptedstay as they were. Accepting keeps the owner's settings for tools alreadyset; new usable tools get the defaults.+## The node++`mcpConnector` (Custom Connector) goes on an agent's Tools and names one+connector (`mcp_connector`, a dropdown of the saved ones). It gives the agent+one tool per tool of that connector that can be used and is on, named+`<connector>__<tool>` with the server's description and input schema+(`ToolNode.tool_bindings`; see [Agent Architecture](./agent_architecture.md)+for how every agent path builds them). Each tool runs with its binding's+settings, which are locked so the model never sets them: `mcp_tool`, `mcp_ask`+(its Ask first), and the labels its card shows (`mcp_label`, `mcp_title`).++- **A call**: the connector is read again, so a tool the server no longer+ offers or the owner turned off since the run began is refused. The+ arguments are checked against the tool's input schema (jsonschema), then+ the tool is called over the connector's transport within `CALL_TIMEOUT_S`+ (300 s). The model gets the answer's text (each part that is not text is+ named) and its structured result; an answer marked as an error comes back+ as the tool's error.+- **Ask first**: the node's `approval` spec holds a call while the employee+ asks first, unless its tool is set not to (`mcp_ask`). A call whose binding+ says nothing asks first. The card names the connector and the tool, and+ reads "Done" or "Not done" once it ran.+- **When settings reach the agent**: the tools are read when an agent's run+ starts, so a tool turned on, or a change to its Ask first, applies from the+ next run. A tool turned off is refused at once.+- CLI agents (Claude Code, Codex) leave the node out; an RLM agent refuses it.+## The page- **Add** on the Connectors page (`CatalogLayout.primaryAction`) opens@@ -142,7 +172,8 @@ set; new usable tools get the defaults.## Known gaps-- No employee uses a connector's tools yet.+- Hiring does not add a connector: an employee uses one only when its+ workflow gets the Custom Connector node in Dev mode.- No OAuth sign-in.- A host's addresses are checked when connecting, not pinned for theconnection.diff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.mdindex c3ec5599..c7eeafe6 100644--- a/docs-internal/normal_mode.md+++ b/docs-internal/normal_mode.md@@ -1094,9 +1094,9 @@ chat's rollback), `lib/__tests__/workflowOps.test.ts` and- Billing has no plans, payment method or invoices: no billing account sitsbehind OpenCompany. A deleted employee's runs leave the month's count,because deleting a workflow deletes its run records.-- A custom (MCP) connector's tools reach no employee yet: the connector is- kept, tested and refreshed, and its tools set, but no hire or agent uses- them.+- Hiring does not add a custom (MCP) connector: an employee uses one only+ when its workflow gets the Custom Connector node (`mcpConnector`) in Dev+ mode.- Skill library changes reach only new hires: an employee keeps the skills itwas hired with, and one hired before the library existed has none, untilthe owner asks them in Talk to add one. The library is shared across usersdiff --git a/server/nodes/mcp/__init__.py b/server/nodes/mcp/__init__.pyindex 60b239ae..76adb209 100644--- a/server/nodes/mcp/__init__.py+++ b/server/nodes/mcp/__init__.py@@ -8,16 +8,20 @@ something employees can use.- ``_credentials.py``: each connector's own card in the credentialscatalogue.- ``_handlers.py``: add, test, refresh, accept or discard what a refresh- found, and remove.+ found, set a tool, and remove.+- ``mcp_connector.py``: the node that gives an agent a connector's tools,+ one per tool (``ToolNode.tool_bindings``)."""from __future__ import annotations-from services.ws_handler_registry import register_ws_handlers+from services.ws_handler_registry import register_option_loader, register_ws_handlersfrom ._credentials import McpConnectorCredentialfrom ._handlers import WS_HANDLERS+from .mcp_connector import McpConnectorNode, load_connectorsregister_ws_handlers(WS_HANDLERS)+register_option_loader("mcpConnectors", load_connectors)-__all__ = ["McpConnectorCredential", "WS_HANDLERS"]+__all__ = ["McpConnectorCredential", "McpConnectorNode", "WS_HANDLERS"]diff --git a/server/nodes/mcp/_client.py b/server/nodes/mcp/_client.pyindex 8a6cf499..5781e854 100644--- a/server/nodes/mcp/_client.py+++ b/server/nodes/mcp/_client.py@@ -44,7 +44,7 @@ from services.netpolicy import (if TYPE_CHECKING:from mcp import ClientSession- from mcp.types import InitializeResult, Tool+ from mcp.types import CallToolResult, InitializeResult, ToolTransport = Literal["streamable_http", "sse"]TRANSPORTS: Tuple[Transport, ...] = ("streamable_http", "sse")@@ -297,6 +297,63 @@ async def read_again(raise ConnectorError(describe(exc, host)) from None+@dataclass+class CallResult:+ """What a tool answered: its text for the model, its structured result+ when it gave one, and whether it says the call failed."""++ text: str+ structured: Optional[Dict[str, Any]]+ is_error: bool+++def check_arguments(schema: Dict[str, Any], arguments: Dict[str, Any]) -> None:+ """Refuse arguments the tool's input schema does not accept."""+ from jsonschema import ValidationError+ from jsonschema.validators import validator_for++ try:+ validator_for(schema)(schema).validate(arguments)+ except ValidationError as exc:+ raise ConnectorError(f"The arguments don't fit the tool: {exc.message}") from None+++def result_text(result: "CallToolResult") -> str:+ """A tool's answer as text for the model: its text parts, and a line+ naming each other part."""+ parts: List[str] = []+ for block in result.content:+ if block.type == "text":+ parts.append(block.text)+ elif block.type == "resource" and getattr(block.resource, "text", None) is not None:+ parts.append(block.resource.text)+ elif block.type == "resource_link":+ parts.append(f"[{block.name}: {block.uri}]")+ else:+ parts.append(f"[{block.type} not shown]")+ return "\n".join(parts)+++async def call_tool(+ url: str,+ sign_in: SignIn,+ transport: Transport,+ name: str,+ arguments: Dict[str, Any],+ *,+ http_transport: Optional[httpx.AsyncBaseTransport] = None,+) -> CallResult:+ """Call one of the server's tools, within ``CALL_TIMEOUT_S``."""+ host = await check_server(url)+ try:+ async with asyncio.timeout(CALL_TIMEOUT_S):+ async with open_session(url, sign_in, transport, http_transport=http_transport) as (session, _init):+ result = await session.call_tool(name, arguments, read_timeout_seconds=timedelta(seconds=CALL_TIMEOUT_S))+ except Exception as exc: # noqa: BLE001 - described below, in words for the owner+ raise ConnectorError(describe(exc, host)) from None+ return CallResult(text=result_text(result), structured=result.structuredContent, is_error=bool(result.isError))++def describe(exc: Optional[BaseException], host: str) -> str:"""A failure to reach or read a server, in words for the owner."""from mcp.shared.exceptions import McpError@@ -385,13 +442,16 @@ def changes(before: List[Dict[str, Any]], after: List[Dict[str, Any]]) -> Dict[s__all__ = ["CALL_TIMEOUT_S",+ "CallResult","ConnectorError","Discovery","SEPARATOR","SignIn","Transport","call_name",+ "call_tool","changes",+ "check_arguments","check_server","describe","discover",diff --git a/server/nodes/mcp/_credentials.py b/server/nodes/mcp/_credentials.pyindex 53f03b9d..693f18af 100644--- a/server/nodes/mcp/_credentials.py+++ b/server/nodes/mcp/_credentials.py@@ -91,8 +91,8 @@ class McpConnectorCredential(Credential):@classmethodasync def is_configured(cls, auth_service: Any, parameters: Dict[str, Any]) -> bool:- """The connector the node names is saved."""- ref = str(parameters.get("connector") or "")+ """The connector the node names (``mcp_connector``) is saved."""+ ref = str(parameters.get("mcp_connector") or "")return slug_of(ref) is not None and bool(await auth_service.has_valid_key(ref))diff --git a/server/nodes/mcp/_store.py b/server/nodes/mcp/_store.pyindex 8239f219..99a48dcd 100644--- a/server/nodes/mcp/_store.py+++ b/server/nodes/mcp/_store.py@@ -46,10 +46,15 @@ def slug_of(ref: str) -> Optional[str]:def new_slug(name: str, url: str) -> str:- """A new connector's slug: from its name, else from its server's host."""+ """A new connector's slug: from its name, else from its server's host.+ It starts with a letter, since its tools' names start with it and some+ models (Gemini) take only a name that starts with a letter."""from slugify import slugify- return slugify(name or (urlsplit(url.strip()).hostname or ""), max_length=SLUG_MAX, separator="-")+ slug = slugify(name or (urlsplit(url.strip()).hostname or ""), max_length=SLUG_MAX, separator="-")+ if slug and not slug[0].isalpha():+ slug = slugify(f"mcp-{slug}", max_length=SLUG_MAX, separator="-")+ return slugdef now() -> str:diff --git a/server/nodes/mcp/mcp_connector.py b/server/nodes/mcp/mcp_connector.pynew file mode 100644index 00000000..f0c5ef1f--- /dev/null+++ b/server/nodes/mcp/mcp_connector.py@@ -0,0 +1,139 @@+"""The custom connector node (``mcpConnector``): on an agent's Tools, it gives+the agent each tool of one custom MCP connector that the owner has on, named+``<connector>__<tool>`` (``tool_bindings``). A call is checked against the+tool's input schema, then sent to the server (``_client.call_tool``).++What a call runs with (``mcp_tool``, ``mcp_ask`` and the labels its card+shows) comes from its binding and is locked: the model never sets it. While+the employee asks first, a call of a tool set to Ask first waits for the+owner (``approval``).+"""++from __future__ import annotations++from typing import Any, Dict, List, Mapping, Optional++from pydantic import BaseModel, ConfigDict, Field++from services.plugin import NodeContext, NodeUserError, Operation, TaskQueue, ToolNode+from services.plugin.approval import ApprovalSpec+from services.plugin.tool import ToolBinding, inline_schema_refs++from ._client import ConnectorError, call_name, call_tool, check_arguments+from ._credentials import McpConnectorCredential+from ._store import get_connector, list_connectors, read_access, slug_of+++class McpConnectorParams(BaseModel):+ mcp_connector: str = Field(+ default="",+ description="The custom connector whose tools the agent may use",+ json_schema_extra={"loadOptionsMethod": "mcpConnectors", "placeholder": "Choose a connector"},+ )+ # Set by each tool's binding, never shown or set by hand.+ mcp_tool: str = Field(default="", json_schema_extra={"hidden": True})+ mcp_ask: bool = Field(default=True, json_schema_extra={"hidden": True})+ mcp_label: str = Field(default="", json_schema_extra={"hidden": True})+ mcp_title: str = Field(default="", json_schema_extra={"hidden": True})++ model_config = ConfigDict(extra="ignore")+++class McpToolInput(BaseModel):+ """A remote tool's arguments, checked against its own input schema."""++ model_config = ConfigDict(extra="allow")+++class McpToolOutput(BaseModel):+ text: str = ""+ structured: Optional[Dict[str, Any]] = None+++async def load_connectors(params: Optional[Dict[str, Any]] = None) -> List[Dict[str, str]]:+ """The saved custom connectors, for the node's dropdown."""+ return [{"name": connector.name, "value": connector.ref} for connector in await list_connectors()]+++class McpConnectorNode(ToolNode):+ type = "mcpConnector"+ display_name = "Custom Connector"+ subtitle = "MCP Tools"+ group = ("tool", "ai")+ description = "Gives an agent the tools of a custom connector added on the Connectors page"+ component_kind = "tool"+ task_queue = TaskQueue.REST_API+ credentials = (McpConnectorCredential,)+ annotations = {"destructive": True, "readonly": False, "open_world": True}+ ui_hints = {"hideRunButton": True}++ Params = McpConnectorParams+ ToolInput = McpToolInput+ Output = McpToolOutput+ server_controlled_fields = frozenset({"mcp_connector", "mcp_tool", "mcp_ask", "mcp_label", "mcp_title"})++ approval = ApprovalSpec(+ channel="Custom connector",+ action="Use a connector tool",+ # A call asks first unless its tool is set not to.+ when=lambda data: data.get("mcp_ask") is not False,+ details=(("Connector", "mcp_label"), ("Tool", "mcp_title")),+ outcome_labels=("Done", "Not done"),+ )++ @classmethod+ async def tool_bindings(cls, parameters: Mapping[str, Any]) -> List[ToolBinding]:+ """One tool per tool of the connector that can be used and is on."""+ ref = str(parameters.get("mcp_connector") or "")+ if slug_of(ref) is None:+ return []+ try:+ connector = await get_connector(ref)+ except ConnectorError:+ return []+ bindings = []+ for tool in connector.tools:+ setting = connector.settings.get(tool["name"]) or {}+ if not tool.get("usable") or not setting.get("enabled"):+ continue+ title = tool.get("title") or tool["name"]+ bindings.append(+ ToolBinding(+ key=tool["name"],+ name=call_name(connector.slug, tool["name"]),+ description=tool.get("description") or title,+ schema=inline_schema_refs(tool["input_schema"]),+ parameters={+ "mcp_tool": tool["name"],+ "mcp_ask": bool(setting.get("ask", True)),+ "mcp_label": connector.name,+ "mcp_title": title,+ },+ )+ )+ return bindings++ @Operation("call")+ async def call(self, ctx: NodeContext, params: McpToolInput | McpConnectorParams) -> McpToolOutput:+ config = ctx.raw.get("_tool_config")+ if not isinstance(params, McpToolInput) or not isinstance(config, McpConnectorParams) or not config.mcp_tool:+ raise NodeUserError("Connect this node to an agent's Tools: its tools are the agent's to call.")+ try:+ connector = await get_connector(config.mcp_connector)+ tool = next((tool for tool in connector.tools if tool["name"] == config.mcp_tool), None)+ if tool is None or not tool.get("usable"):+ raise ConnectorError(f"{connector.name} no longer offers {config.mcp_tool}.")+ if not (connector.settings.get(tool["name"]) or {}).get("enabled"):+ raise ConnectorError(f"The owner turned {config.mcp_title or tool['name']} off.")+ arguments = params.model_dump()+ check_arguments(tool["input_schema"], arguments)+ url, sign_in = await read_access(connector)+ result = await call_tool(url, sign_in, connector.meta.get("transport") or "streamable_http", tool["name"], arguments)+ except ConnectorError as exc:+ raise NodeUserError(str(exc)) from None+ if result.is_error:+ raise NodeUserError(result.text or f"{config.mcp_title or config.mcp_tool} reported an error.")+ return McpToolOutput(text=result.text, structured=result.structured)+++__all__ = ["McpConnectorNode", "McpConnectorParams", "McpToolInput", "McpToolOutput", "load_connectors"]diff --git a/server/nodes/mcp/meta.json b/server/nodes/mcp/meta.jsonnew file mode 100644index 00000000..3dde8af2--- /dev/null+++ b/server/nodes/mcp/meta.json@@ -0,0 +1,6 @@+{+ "color": "#8be9fd",+ "icons": {+ "mcpConnector": "lucide:Plug"+ }+}diff --git a/server/tests/nodes/test_mcp_connector.py b/server/tests/nodes/test_mcp_connector.pyindex f365b322..064128a4 100644--- a/server/tests/nodes/test_mcp_connector.py+++ b/server/tests/nodes/test_mcp_connector.py@@ -16,9 +16,12 @@ import pytestfrom mcp.server.fastmcp import FastMCPfrom mcp.types import Tool, ToolAnnotations-from nodes.mcp import _client, _handlers+from nodes.mcp import _client, _handlers, mcp_connectorfrom nodes.mcp._client import ConnectorError, SignIn, check_server, snapshotsfrom nodes.mcp._credentials import McpConnectorCredential+from nodes.mcp._store import new_slug+from nodes.mcp.mcp_connector import McpConnectorNode+from services.plugin import NodeContextURL = "http://127.0.0.1:8931/mcp"SOCKET = SimpleNamespace(scope={"path": "/ws/status"}, state=SimpleNamespace(user_id=None))@@ -180,6 +183,12 @@ class TestSignIn:assert SignIn.load(sign_in.dump()) == sign_in+def test_a_slug_starts_with_a_letter_as_a_tool_name_must():+ assert new_slug("Orders", URL) == "orders"+ assert new_slug("", URL) == "mcp-127-0-0-1"+ assert new_slug("3M Orders", URL) == "mcp-3m-orders"++def test_a_tool_no_model_could_call_is_kept_with_the_reason():tools = [Tool(name="ok", inputSchema={"type": "object", "properties": {}}),@@ -344,3 +353,41 @@ class TestTheConnectorsPage:internal = SimpleNamespace(scope={"path": "/ws/internal"})result = await _handlers.handle_mcp_connector_add({"url": URL}, internal)assert result == {"success": False, "error": "Connectors are managed from the app."}+++LOOKUP = {"mcp_connector": "mcp:orders", "mcp_tool": "lookup_order", "mcp_ask": False, "mcp_label": "Orders", "mcp_title": "Look up an order"}+++class TestTheNode:+ async def test_it_gives_an_agent_each_tool_that_is_on(self, auth, monkeypatch):+ async with serving(monkeypatch, orders_server()):+ await add()+ await _handlers.handle_mcp_connector_set_tool({"ref": "mcp:orders", "tool": "send_reply", "enabled": False}, SOCKET)+ [binding] = await McpConnectorNode.tool_bindings({"mcp_connector": "mcp:orders"})+ assert binding.name == "orders__lookup_order"+ assert binding.parameters == {"mcp_tool": "lookup_order", "mcp_ask": False, "mcp_label": "Orders", "mcp_title": "Look up an order"}+ assert binding.schema["properties"]["order"]["type"] == "string"+ # No connector chosen, or one that is gone: no tools.+ assert await McpConnectorNode.tool_bindings({}) == []+ assert await McpConnectorNode.tool_bindings({"mcp_connector": "mcp:gone"}) == []++ async def test_a_call_reaches_the_server_with_arguments_its_tool_accepts(self, auth, monkeypatch):+ node = McpConnectorNode()+ async with serving(monkeypatch, orders_server()) as transport:+ await add()+ monkeypatch.setattr(mcp_connector, "call_tool", functools.partial(_client.call_tool, http_transport=transport))+ result = await node.execute_as_tool({"order": "A1"}, LOOKUP, NodeContext(node_id="n1", node_type="mcpConnector", raw={}))+ assert result["text"] == "Order A1: 2 books"+ refused = await node.execute_as_tool({"order": 5}, LOOKUP, NodeContext(node_id="n1", node_type="mcpConnector", raw={}))+ assert refused == {"error": "The arguments don't fit the tool: 5 is not of type 'string'"}+ # A tool the owner turned off since the agent got it is not called.+ await _handlers.handle_mcp_connector_set_tool({"ref": "mcp:orders", "tool": "lookup_order", "enabled": False}, SOCKET)+ off = await node.execute_as_tool({"order": "A1"}, LOOKUP, NodeContext(node_id="n1", node_type="mcpConnector", raw={}))+ assert off == {"error": "The owner turned Look up an order off."}++ def test_a_tool_set_to_ask_first_waits_while_the_employee_asks_first(self):+ spec = McpConnectorNode.approval+ assert spec.sends({"mcp_ask": True}) and not spec.sends({"mcp_ask": False})+ # Without its binding's word, a call asks first.+ assert spec.sends({})+ assert spec.preview(LOOKUP)["details"] == [{"label": "Connector", "value": "Orders"}, {"label": "Tool", "value": "Look up an order"}]diff --git a/server/tests/test_plugin_self_containment.py b/server/tests/test_plugin_self_containment.pyindex 1452293f..aff63206 100644--- a/server/tests/test_plugin_self_containment.py+++ b/server/tests/test_plugin_self_containment.py@@ -67,6 +67,7 @@ _MIGRATED_PLUGINS = ("gcloud","github","google",+ "mcp","microsoft","stripe","telegram",@@ -85,6 +86,7 @@ _PLUGINS_WITH_HANDLERS = ("gcloud","github","google",+ "mcp","microsoft","stripe","telegram",