diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a22956cb..4915c8691 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -233,6 +233,11 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version machine's upgrade agent starts and stops them), and agents do the same with `PUT /api/v1/admin/services/` or the MCP tools `services` and `set_service`. A server whose spec says `keep: true` keeps one session between calls ([The browser](docs/assistant.md#the-browser), [Optional containers](docs/assistant.md#optional-containers)). +- **MCP servers in Settings, and for agents.** Settings › AI assistant now lists the MCP servers the assistant calls, + each with how many of its tools are on and a link to its page, next to Add MCP server and the switches for the MCP + runner and the browser. Agents list them with the MCP tool `mcp_servers` and add one, ready-made or their own, with + `add_mcp_server` (an admin's API key with the write scope) + ([Adding an MCP server](docs/assistant.md#adding-an-mcp-server)). - **Describe an automation in words.** `POST /api/v1/automations/draft` asks the model once to turn a sentence into a draft automation to try and save, and says what didn't fit and what it couldn't express ([Describe it in words](docs/automations.md#describe-it-in-words)). diff --git a/docs/assistant.md b/docs/assistant.md index def078186..190a06a6d 100644 --- a/docs/assistant.md +++ b/docs/assistant.md @@ -747,6 +747,13 @@ runs (until then its switch is there to turn it on). **GitHub** puts GitHub's ow `GET /api/v1/extensions/mcp/presets` (admins), each with the spec to save and, for the browser, whether its container is on and answering. +**Settings › AI assistant › MCP servers** lists the servers added, each with how many of its tools the assistant is +offered and a link to its page, with **Add MCP server** and the switches that run the MCP runner and the browser on +this machine. Agents do the same with the MCP tools `mcp_servers`, which lists the servers (header and env names, never +their values) and the ready-made ones, and `add_mcp_server`, which adds one, a ready-made one (`preset`, with `values` +for its token) or its own (`server`), checked as the form checks it. Adding one takes an admin's API key with the +write scope; an app given access (OAuth) can't add one, even an admin's. + Header and environment values whose names say they carry a credential (Authorization, API keys, tokens, secrets, passwords, cookies, sessions) are sealed when the server is saved, with the server's key (as notification targets and sources are, since an MCP server belongs to the whole install rather than a namespace), bound to the extension, the @@ -789,8 +796,10 @@ The browser is a headless Chromium the assistant drives over MCP: it opens pages in forms. It is [Playwright MCP](https://github.com/microsoft/playwright-mcp) (Apache-2.0), in a container of its own (the optional `browser` profile, `mcr.microsoft.com/playwright/mcp`, pinned in the compose file: about 400 MB to download, and at most 1 GB of memory). It's off until you turn it on: **Run the browser on this -machine** under **Ready-made** in **Add MCP server**, then **Add Browser**, which adds it as the MCP server `browser` -(its tools are `browser__browser_navigate`, `browser__browser_snapshot`, `browser__browser_click` and so on). +machine** under **Ready-made** in **Add MCP server** (or in Settings › AI assistant › MCP servers), then +**Add Browser**, which adds it as the MCP server `browser` (its tools are `browser__browser_navigate`, +`browser__browser_snapshot`, `browser__browser_click` and so on). It's a browser on this machine with nobody signed in, +not [the assistant in your browser](browser-assistant.md), which uses your own browser where you are signed in. - **Its sandbox.** None of Lens's data, keys or database; every capability dropped, a read-only image, memory and process limits, and its profile (cookies, history) in memory only, gone when it stops (after an hour unused, or with diff --git a/docs/mcp.md b/docs/mcp.md index d52ef6998..b07a19171 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -45,9 +45,10 @@ Each namespace can have its own server, at `/mcp/` (`https://lens.exa that should see that namespace and nothing else: a family assistant, a project's coding agent, a client's app. It has the same tools, but sees only that namespace, whatever else the person who signs the agent in can read. Tools that take a namespace use this one when none is named, `list_namespaces` and `list_files` show only it, and the tools -about the server itself (`file_storage`, `monitoring`, `services`, `sandbox_gateway`, `install_settings` and the -ones that change them) aren't there, even for admins. Nor are the person's own conversations (`list_chats`, -`read_chat`, `rename_chat`, `export_chat`), which belong to no namespace. An admin counts as an owner of the namespace there. +about the server itself (`file_storage`, `monitoring`, `services`, `mcp_servers`, `sandbox_gateway`, `install_settings` +and the ones that change them) aren't there, even for admins. Nor are the person's own conversations (`list_chats`, +`read_chat`, `rename_chat`, `export_chat`), which belong to no namespace. An admin counts as an owner of the +namespace there. It is off until an owner of the namespace turns it on: **Admin → Namespaces →** the namespace **→ Connect apps**, which also copies its address, or `PATCH /api/v1/namespaces//integrations` with `{"mcp": true}`, or an agent's @@ -133,6 +134,8 @@ For an app that speaks OpenAI's API rather than MCP, the namespace can also answ | `set_service` | start or stop one of them (`mcp`, `browser` or `monitoring`): the machine's upgrade agent does it. Admins only, with a write-scope token | | `picture_descriptions` | what describes the pages and shots of resources ([Descriptions](configuration.md#descriptions)): the LLM provider's model that can see images, or Florence-2 or Moondream on this server, its model, whether it's ready and why not, and the engines there are. Admins only | | `set_picture_descriptions` | choose what describes pictures (`engine` `llm`, `florence-2` or `moondream`), the provider's `vision_model`, Florence-2's size (`florence_model`), which Moondream (`moondream_model`) and `describe_max`. Admins only, with a write-scope token | +| `mcp_servers` | the MCP servers the assistant calls ([Adding an MCP server](assistant.md#adding-an-mcp-server)): each one's address or command, the names of its headers and env (never their values), whether it's on, its tools and those switched off, and its page; and the ready-made ones (browser, github), whether each is added and what it needs. Admins only | +| `add_mcp_server` | add one: a ready-made one (`preset`, with `values` for its token) or your own (`server`: `{url, headers}` or `{command, args, env}`, with `off`, `ask` and `keep`); Lens lists its tools first, so it must answer, and seals its tokens. Admins only, with an API key that has the write scope (not an app given access) | | `install_settings` | whether other devices on the network reach Lens and its edition (full or lean), whether the machine's upgrade agent can change them, and the install line to run when it can't. Admins only | | `set_install_settings` | open Lens to the network or keep it to this machine, or change the edition: the machine sets itself up again and Lens restarts ([Updates](updates.md#setting-the-machine-up-again)). Admins only, with a write-scope token | | `news_feeds` | the news feeds (RSS or Atom) Lens follows, the namespaces each brings posts into and how the last scan went; addresses stay sealed. Admins only | @@ -158,7 +161,8 @@ which records an undoable change (proposed by default), `undo_graph_change`, `ed app (merges and deletes can be undone), `write_note`, which adds a note, `create_podcast`, which queues an episode, `create_feed` and `publish_to_feed`, which make and fill a [published feed](feeds.md), `write_spec`, which queues a spec, `set_nsfw` and `mark_nsfw`, which change [NSFW classification](nsfw.md) (owners or admins, and -editors), `set_namespace_integrations`, which turns a namespace's own MCP server or chat completions on or off (owners), `set_picture_descriptions`, which changes what describes pictures (admins), `set_file_storage`, which changes where new files are kept (admins), `subscribe_feed` and `unsubscribe_feed`, which follow and stop following news feeds (admins), and `set_monitoring`, `set_service`, +editors), `set_namespace_integrations`, which turns a namespace's own MCP server or chat completions on or off (owners), `set_picture_descriptions`, which changes what describes pictures (admins), `set_file_storage`, which changes where new files are kept (admins), `add_mcp_server`, which adds an +MCP server (admins), `subscribe_feed` and `unsubscribe_feed`, which follow and stop following news feeds (admins), and `set_monitoring`, `set_service`, `set_sandbox_gateway` (the [code sandbox](assistant.md#code-sandbox)'s gateway) and `set_install_settings`, which have the machine change how Lens runs (admins). Importing stays in the web app and the API. diff --git a/fastapi_backend/app/api/mcp_tools.py b/fastapi_backend/app/api/mcp_tools.py index 2ed601155..ca42448ce 100644 --- a/fastapi_backend/app/api/mcp_tools.py +++ b/fastapi_backend/app/api/mcp_tools.py @@ -51,6 +51,7 @@ decide, descriptions, events, + extensions, feeds, filetree, florence, @@ -58,6 +59,7 @@ integrations, library, manual, + mcp_servers, monitoring, moondream, notebook, @@ -2669,6 +2671,125 @@ def set_sandbox_gateway(ctx: Context, on: bool) -> dict[str, Any]: return got +# ---------- the MCP servers the assistant calls (admins) ---------- +def _extension_me(ctx: Context) -> dict[str, Any]: + """Who is asking, as extensions.py checks it: an app given access (OAuth) doesn't count as an admin there.""" + u = ctx.user + return extensions.who(u.id, u.email, u.admin and u.via != "oauth", u.roles) + + +def _server_line(ctx: Context, g: dict[str, Any]) -> dict[str, Any]: + s = g.get("spec") or {} + return store.clean( + { + "id": g["id"], + "name": g["name"], + "title": g.get("title"), + "description": g.get("description"), + "enabled": bool(g.get("enabled")), + "url": s.get("url"), + "command": s.get("command"), + "args": s.get("args"), + "headers": sorted(s.get("headers") or {}) or None, # names only: their values are never shown + "env": sorted(s.get("env") or {}) or None, + "tools": [t["name"] for t in s.get("tools") or []], + "off": s.get("off") or [], + "keep": bool(s.get("keep")), + "page": f"{ctx.web}/extensions/{g['id']}", + } + ) + + +@tool( + "mcp_servers", + "MCP servers", + "The MCP servers the assistant can call, added in Extensions: each one's address or command, the names of its " + "headers and env (never their values), whether it's on, its tools and the ones switched off, and its page in the " + "web app; and the ready-made ones Lens knows (browser, github), whether each is added and what it needs. Admins " + "only.", + admin=True, +) +def mcp_servers_list(ctx: Context) -> dict[str, Any]: + if not ctx.user.admin: + raise ToolError("only admins see and add MCP servers") + added = [_server_line(ctx, g) for g in extensions.visible(ctx.db, _extension_me(ctx), "mcp")] + ready = [] + for p in mcp_servers.presets(): + have = any(x["name"] == p["name"] or (x.get("url") and x["url"] == p["spec"].get("url")) for x in added) + ready.append( + store.clean( + { + "preset": p["name"], + "label": p["label"], + "description": p["description"], + "added": have, + "values": p["fill"] or None, # what add_mcp_server needs typed in + "service": services.view(ctx.db, p["needs"]) if p["needs"] else None, + } + ) + ) + return {"servers": added, "ready_made": ready, "add": f"{ctx.web}/extensions/new/mcp"} + + +@tool( + "add_mcp_server", + "Add an MCP server", + "Add an MCP server the assistant can call. A ready-made one: preset browser (once its container runs: set_service) " + 'or github, with values for what it needs ({"GITHUB_TOKEN": "..."}). Or your own: server {url, headers} for one on ' + "the network (Streamable HTTP), or {command, args, env} for one that runs as a program in the MCP runner; off lists " + "tools to switch off, ask {tool: true or false} which ask first, keep true one session for all its calls. Lens " + "asks the server for its tools before saving it, so it must answer. Tokens are sealed and never shown again. " + "Admins only, with an API key that has the write scope (an app given access can't add one).", + Arg("preset", "string", "a ready-made server", enum=tuple(p["name"] for p in mcp_servers.presets())), + Arg("name", "string", "its name: lowercase letters, digits and _ (its tools are called __)", max_length=41), + Arg("server", "object", "{url, headers} or {command, args, env}, with off, ask and keep; with a preset, what to change"), + Arg("values", "object", "the values a ready-made server, or the ${NAME}s in your own, need typed in, by name"), + Arg("description", "string", "what it's for", max_length=1024), + writes=True, + admin=True, +) +def add_mcp_server( + ctx: Context, + preset: str | None = None, + name: str | None = None, + server: dict[str, Any] | None = None, + values: dict[str, Any] | None = None, + description: str | None = None, +) -> dict[str, Any]: + if not ctx.user.admin: + raise ToolError("only admins see and add MCP servers") + if ctx.user.via == "oauth": + raise ToolError("an app given access can't add MCP servers, even an admin's: use an admin's API key, or the web app") + if not ctx.user.can_write: + raise ToolError("this token is read-only: ask for a token with the write scope to add one") + spec = dict(server or {}) + if preset: + p = next(x for x in mcp_servers.presets() if x["name"] == preset) + if p["needs"]: + s = services.view(ctx.db, p["needs"]) + if not s["running"]: + raise ToolError( + f"the {s['label'].lower()} isn't running yet: turn it on with set_service ({p['needs']}), and add " + "it once services says it is" + ) + spec = {**p["spec"], **spec} + name, description = name or p["name"], description or p["description"] + elif not spec: + raise ToolError("give a preset, or the server: {url, headers} or {command, args, env}") + if not name: + raise ToolError("name it: lowercase letters, digits and _") + spec, missing = mcp_servers.filled(spec, {k: v for k, v in (values or {}).items() if isinstance(v, str)}) + if missing: + raise ToolError(f"type in {', '.join(missing)} in values") + manifest = {"name": name, "kind": "mcp", **({"description": description} if description else {}), **spec} + try: + eid = extensions.create(ctx.db, _extension_me(ctx), manifest) + except (ValueError, PermissionError) as e: + raise ToolError(str(e)) from None + auth.audit(ctx.db, ctx.user.as_audit(), "extension.create", f"extension:{eid}", {"origin": "code", "via": "mcp"}) + return _server_line(ctx, extensions.visible_one(ctx.db, _extension_me(ctx), eid)) + + # ---------- how install.sh set this machine up: reachable on the network, and the edition (admins) ---------- @tool( "install_settings", diff --git a/fastapi_backend/app/domain/mcp_servers.py b/fastapi_backend/app/domain/mcp_servers.py index 1025c34dd..91f8b51c4 100644 --- a/fastapi_backend/app/domain/mcp_servers.py +++ b/fastapi_backend/app/domain/mcp_servers.py @@ -308,6 +308,31 @@ def presets(): ] +def filled(spec, values): + """A server's spec with the values typed in for its ${NAME}s put in their place (address, args, headers, env), and + the names still missing a value.""" + missing = [] + + def put(text): + def one(m): + if isinstance(values.get(m.group(1)), str) and values[m.group(1)]: + return values[m.group(1)] + missing.append(m.group(1)) + return m.group(0) + + return PLACEHOLDER_RX.sub(one, text) if isinstance(text, str) else text + + out = dict(spec) + if out.get("url"): + out["url"] = put(out["url"]) + if out.get("args"): + out["args"] = [put(a) for a in out["args"]] + for field, _ in FIELDS: + if out.get(field): + out[field] = {k: put(v) for k, v in out[field].items()} + return out, sorted(set(missing)) + + # ---------- upgrading ---------- def migrate_seal(db): """Upgrade step: seal the credentials MCP servers kept in plain text in their headers and env, in every version of diff --git a/fastapi_backend/tests/api/test_mcp.py b/fastapi_backend/tests/api/test_mcp.py index fd0027c52..31f48df85 100644 --- a/fastapi_backend/tests/api/test_mcp.py +++ b/fastapi_backend/tests/api/test_mcp.py @@ -95,6 +95,7 @@ def test_clients_are_sent_to_sign_in(client, app, env): "set_monitoring", "set_service", "set_sandbox_gateway", + "add_mcp_server", "set_install_settings", "subscribe_feed", "unsubscribe_feed", diff --git a/fastapi_backend/tests/api/test_mcp_servers.py b/fastapi_backend/tests/api/test_mcp_servers.py index 4e7d2e1d1..fc28c7a66 100644 --- a/fastapi_backend/tests/api/test_mcp_servers.py +++ b/fastapi_backend/tests/api/test_mcp_servers.py @@ -481,3 +481,47 @@ def use(name): monkeypatch.setattr(mcp_client, "_kept", {}) plain = {**tools["browser__browser_snapshot"]["spec"]["run"], "keep": None} assert len({mcp_client.call(plain, {})["text"].split()[0] for _ in range(2)}) == 2 and not mcp_client._kept + + +def test_agents_list_and_add_servers(app, db, cfg, folder, new_client, server, monkeypatch): + """Over MCP, an admin's agent lists the servers and the ready-made ones, and adds one: its own, or GitHub with its + token typed in, checked as the web app's form is (it must answer, its token sealed and never shown).""" + from app.domain import services + from tests.api.test_mcp import rpc + + s = Assist(app, db, cfg, folder, new_client) + + def mcp(who, tool, **args): + c, h = s.cl[who] + res = rpc(c, h, "tools/call", {"name": tool, "arguments": args})["result"] + return json.loads(res["content"][0]["text"]) if res["isError"] else res["structuredContent"] + + assert "only admins" in mcp("editor", "mcp_servers")["error"] + assert "only admins" in mcp("editor", "add_mcp_server", preset="github", values={"GITHUB_TOKEN": "t0ken"})["error"] + got = mcp("admin", "mcp_servers") + assert got["servers"] == [] and got["add"].endswith("/extensions/new/mcp") + browser, github = got["ready_made"] + assert (browser["preset"], browser["added"], browser["service"]["profile"]) == ("browser", False, "browser") + assert (github["preset"], github["values"], "service" in github) == ("github", ["GITHUB_TOKEN"], False) + + # its own server, with a value typed in for its ${TOKEN} + spec = {"url": "https://mcp.example.com/mcp", "headers": {"Authorization": "Bearer ${TOKEN}"}, "off": ["create-issue"]} + assert "type in TOKEN in values" in mcp("admin", "add_mcp_server", name="tracker", server=spec)["error"] + added = mcp("admin", "add_mcp_server", name="tracker", server=spec, values={"TOKEN": "t0ken"}, description="Issues") + assert (added["tools"], added["off"], added["headers"]) == (["search", "create-issue"], ["create-issue"], ["Authorization"]) + assert added["enabled"] is True and added["page"].endswith(f"/extensions/{added['id']}") + assert mcp_servers.is_sealed(extensions.get(db, added["id"])["spec"]["headers"]["Authorization"]) + assert "t0ken" not in json.dumps(mcp("admin", "mcp_servers")) + again = mcp("admin", "add_mcp_server", name="tracker", server=spec, values={"TOKEN": "t0ken"}) + assert "already called" in again["error"] + assert "answered 401" in mcp("admin", "add_mcp_server", name="wrong", server=spec, values={"TOKEN": "nope"})["error"] + + # GitHub, ready-made: its name, address and description come with it + gh = mcp("admin", "add_mcp_server", preset="github", values={"GITHUB_TOKEN": "t0ken"}) + assert (gh["name"], gh["url"]) == ("github", "https://api.githubcopilot.com/mcp/") + assert [p["added"] for p in mcp("admin", "mcp_servers")["ready_made"]] == [False, True] + # the browser waits for its container + assert "isn't running yet" in mcp("admin", "add_mcp_server", preset="browser")["error"] + monkeypatch.setattr(services, "running", lambda profile: True) + assert "isn't running yet" not in mcp("admin", "add_mcp_server", preset="browser")["error"] # on to the server + assert "give a preset" in mcp("admin", "add_mcp_server", name="x")["error"] diff --git a/nextjs-frontend/__tests__/mcp-server-ui.test.tsx b/nextjs-frontend/__tests__/mcp-server-ui.test.tsx index 0b604ee01..ec5834219 100644 --- a/nextjs-frontend/__tests__/mcp-server-ui.test.tsx +++ b/nextjs-frontend/__tests__/mcp-server-ui.test.tsx @@ -6,6 +6,7 @@ import type { ReactNode } from "react"; import { Extensions, Updates } from "@/app/openapi-client"; import { ExtensionEditor } from "@/components/extensions/extension-editor"; import { McpServerForm } from "@/components/extensions/mcp-server-form"; +import { McpServers, toolCount } from "@/components/settings/mcp-servers"; import { TooltipProvider } from "@/components/ui/tooltip"; jest.mock("@/app/openapi-client", () => ({ @@ -19,6 +20,7 @@ jest.mock("@/app/openapi-client", () => ({ updateExtension: jest.fn(), deleteExtension: jest.fn(), mcpPresets: jest.fn(), + listExtensions: jest.fn(), }, Updates: { listServices: jest.fn(), setService: jest.fn() }, })); @@ -275,3 +277,47 @@ describe("adding an MCP server", () => { expect(screen.queryByLabelText("Tool")).not.toBeInTheDocument(); }); }); + +describe("MCP servers in Settings", () => { + beforeEach(() => jest.clearAllMocks()); + + it("lists each server with its tools, and the containers' switches", async () => { + const spec = (n: number, off: string[] = []) => ({ + tools: Array.from({ length: n }, (_, i) => ({ name: `t${i}` })), + off, + }); + m(Extensions.listExtensions).mockReturnValue( + ok([ + { id: 3, kind: "mcp", name: "tracker", title: "Tracker", enabled: true, spec: spec(2, ["t1"]) }, + { id: 4, kind: "mcp", name: "browser", enabled: false, spec: spec(1) }, + { id: 5, kind: "skill", name: "notes", enabled: true, spec: {} }, + ]), + ); + m(Updates.listServices).mockReturnValue( + ok({ + services: [ + { ...service, profile: "mcp", label: "MCP runner" }, + { ...service, on: true, running: true, state: "done" }, + ], + }), + ); + wrap(); + const tracker = await screen.findByRole("link", { name: "Tracker" }); + expect(tracker).toHaveAttribute("href", "/extensions/3"); + expect(screen.getByText("1 of 2 tools")).toBeInTheDocument(); + expect(screen.getByRole("link", { name: "browser" })).toHaveAttribute("href", "/extensions/4"); + expect(screen.getByText("1 tool, switched off")).toBeInTheDocument(); + expect(screen.queryByText("notes")).not.toBeInTheDocument(); + expect(screen.getByRole("link", { name: "Add MCP server" })).toHaveAttribute("href", "/extensions/new/mcp"); + expect(await screen.findByRole("switch", { name: "Run the MCP runner on this machine" })).not.toBeChecked(); + expect(screen.getByRole("switch", { name: "Run the browser on this machine" })).toBeChecked(); + }); + + it("says when there are none", async () => { + m(Extensions.listExtensions).mockReturnValue(ok([])); + m(Updates.listServices).mockReturnValue(ok({ services: [] })); + wrap(); + expect(await screen.findByText("None yet.")).toBeInTheDocument(); + expect(toolCount(12, 0)).toBe("12 tools"); + }); +}); diff --git a/nextjs-frontend/components/settings/bodies.tsx b/nextjs-frontend/components/settings/bodies.tsx index 72cb3aee2..034a52d06 100644 --- a/nextjs-frontend/components/settings/bodies.tsx +++ b/nextjs-frontend/components/settings/bodies.tsx @@ -12,6 +12,7 @@ import { BackupsPanel } from "@/components/settings/backups-panel"; import { ComponentsStatus } from "@/components/settings/components-status"; import { EditionChoice, NetworkReach } from "@/components/settings/install-settings"; import { LogViewer } from "@/components/settings/log-viewer"; +import { McpServers } from "@/components/settings/mcp-servers"; import { AllTokens } from "@/components/account/all-tokens"; import { ACCESS } from "@/components/iiif/metadata-model"; import { RIGHTS } from "@/components/iiif/rights"; @@ -2680,6 +2681,7 @@ function AiBody({ ctx }: { ctx: BodyCtx }) { + e.kind === "mcp"); + return ( +
+ MCP servers +

+ Other programs and services whose tools the assistant calls. A server’s page switches each of its tools on or + off and says which ask first. +

+ {list.isError ? ( + {list.error.message} + ) : servers.length ? ( +
    + {servers.map((e) => { + const tools = ((e.spec.tools as unknown[]) ?? []).length; + const off = ((e.spec.off as unknown[]) ?? []).length; + return ( +
  • + + {e.title ?? e.name} + + + {toolCount(tools, off)} + {e.enabled ? "" : ", switched off"} + +
  • + ); + })} +
+ ) : ( + !list.isPending &&

None yet.

+ )} + + + +
+ ); +} diff --git a/threat-model.json b/threat-model.json index 210450d6e..694ca7a5c 100644 --- a/threat-model.json +++ b/threat-model.json @@ -121,7 +121,7 @@ "entry_points": [ "chat, /graph/ask, MCP tools", "extensions (prompt, graph and http tools, hooks), custom nodes including template nodes", - "MCP servers: POST /extensions/mcp/read and /mcp/test, GET /extensions/mcp/presets, saving an extension of kind mcp, PATCH /extensions/{id}/tools", + "MCP servers: POST /extensions/mcp/read and /mcp/test, GET /extensions/mcp/presets, saving an extension of kind mcp, PATCH /extensions/{id}/tools, MCP mcp_servers and add_mcp_server", "Python code tools, shipped and admin-created templates, workflows, pipelines, routines", "Lens extension side panel", "automations", @@ -525,7 +525,7 @@ "source": "docs/assistant.md \"other people's run only when an admin shared them\"" }, { - "entry_point": "MCP servers: POST /extensions/mcp/read and /mcp/test, GET /extensions/mcp/presets, saving an extension of kind mcp, PATCH /extensions/{id}/tools", + "entry_point": "MCP servers: POST /extensions/mcp/read and /mcp/test, GET /extensions/mcp/presets, saving an extension of kind mcp, PATCH /extensions/{id}/tools, MCP mcp_servers and add_mcp_server", "parameter": "config text (JSON or YAML), a server's address and headers, or a command, its arguments and env; a tool name and its switches", "attacker_controllable": "no", "component": "assistant", diff --git a/threat-model.md b/threat-model.md index cf84fb850..dc575fea3 100644 --- a/threat-model.md +++ b/threat-model.md @@ -304,7 +304,7 @@ classified by gate only *(inferred, Q8)*; unread modules are listed in Q34. | chat, `/graph/ask`, MCP tools | prompt text; model-chosen tool calls | yes; also indirectly through content | data, x-prompt-injection | none; what people say to Lens, in the web app or a chat app, reaches automations as outside text (`chat.message`, `lens.untrusted`) | *(documented, docs/assistant.md "limited to what the person can read")* | | Lens extension side panel | answers shown there (model text that can repeat third-party text), the sign-in coming back | yes, indirectly through content | data, x-prompt-injection | none; answers render as Markdown cleaned by DOMPurify (no scripts, images or forms; only http and https links), and the sign-in checks its `state` and PKCE | *(documented, extensions/browser/src/core/assistant.js answerHtml docstring "cleaned of anything that could run or fetch on its own")* | | extensions (prompt, graph and `http` tools, hooks), custom nodes including `template` nodes (Q23) | tool spec, graph JSON, template text | yes, any writer for their own; sharing is gated | callback/code (declarative) | person enables only extensions they trust | *(documented, docs/assistant.md "other people's run only when an admin shared them")* | -| MCP servers: `POST /extensions/mcp/read` (a config pasted from another app), `GET /extensions/mcp/presets` (ready-made ones), `POST /extensions/mcp/test`, saving an extension of kind `mcp`, `PATCH /extensions/{id}/tools` | config text (JSON or YAML), a server's address and headers, or a command, its arguments and env; a tool name and its switches | reading a config: any signed-in person (nothing is reached or run); testing, saving and switching: admins only | data, x-network-destination, x-credential, callback/code (a command) | admin is trusted with the address and the command; reading parses text only; a command runs only in the MCP runner, never next to Lens; credential values are sealed to the extension and where they go, and shown as `••••` (P-SECRETS); a tool switched off isn't offered, and every MCP tool still asks first after outside text (P-INJECTION-EGRESS); a server whose spec says `keep` reuses one session for every caller, which is the server's like its address and token | *(documented, docs/assistant.md "Adding an MCP server")* | +| MCP servers: `POST /extensions/mcp/read` (a config pasted from another app), `GET /extensions/mcp/presets` (ready-made ones), `POST /extensions/mcp/test`, MCP `mcp_servers` and `add_mcp_server`, saving an extension of kind `mcp`, `PATCH /extensions/{id}/tools` | config text (JSON or YAML), a server's address and headers, or a command, its arguments and env; a tool name and its switches | reading a config: any signed-in person (nothing is reached or run); testing, saving and switching: admins only (adding over MCP: an admin's API key with the write scope, never an app given access) | data, x-network-destination, x-credential, callback/code (a command) | admin is trusted with the address and the command; reading parses text only; a command runs only in the MCP runner, never next to Lens; credential values are sealed to the extension and where they go, and shown as `••••` (P-SECRETS); a tool switched off isn't offered, and every MCP tool still asks first after outside text (P-INJECTION-EGRESS); a server whose spec says `keep` reuses one session for every caller, which is the server's like its address and token | *(documented, docs/assistant.md "Adding an MCP server")* | | Python code tools, shipped and admin-created templates, workflows, pipelines, routines | Python, Jinja source, regexes | admin only | callback/code | admin is trusted | *(maintainer, 2026-10)* | | MQTT 1883, syslog 5514, `POST /sensors/push/{token}/{stream}` | payloads, hub logins, token in the path | yes, once enabled | data, size/rate, x-credential, x-prompt-injection | admin enables; operator firewalls; readings, alert patterns and new devices reach automations as outside text (`lens.untrusted`) | *(documented, docs/sensors.md "Sensors are off until an admin turns them on")* | | `POST /automations/hooks/{token}` (an automation's webhook) | body (JSON, a form's text fields or text), query, Standard Webhooks headers, token in the path | yes, anyone given the address | data, size/rate, x-credential, x-prompt-injection | no hook exists until an automation with a webhook trigger is saved; the token is 256 random bits kept only as a hash, and revoked with its trigger; 64 KB and 60 calls a minute per hook; a signature, when sent (or required by a `signed` hook), must match the hook's sealed secret within five minutes; a retried message id is logged once; what was sent is outside text (`lens.untrusted`), wrapped as data in prompts | *(documented, docs/automations.md "No webhook exists until an automation with such a trigger is saved")* | diff --git a/threat-model.yaml b/threat-model.yaml index 05ec43df2..27d39d767 100644 --- a/threat-model.yaml +++ b/threat-model.yaml @@ -447,7 +447,7 @@ entry_points: obligation_id: enable-only-trusted-extensions caller_must_enforce: "person enables only extensions they trust" provenance: {kind: documented, source: 'docs/assistant.md "other people''s run only when an admin shared them"'} - - id: "MCP servers: POST /extensions/mcp/read and /mcp/test, GET /extensions/mcp/presets, saving an extension of kind mcp, PATCH /extensions/{id}/tools" + - id: "MCP servers: POST /extensions/mcp/read and /mcp/test, GET /extensions/mcp/presets, saving an extension of kind mcp, PATCH /extensions/{id}/tools, MCP mcp_servers and add_mcp_server" component: assistant parameters: - name: "config text (JSON or YAML), a server's address and headers, or a command, its arguments and env; a tool name and its switches"