Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(plugins): agent integration — skill resources, agent trigger, mcp transport (MUL-6350 PR 4) (#7242)
Jiayuan Zhang4bf3c73a150e
diff --git a/examples/plugins/deploy-sentinel/README.md b/examples/plugins/deploy-sentinel/README.mdnew file mode 100644index 0000000000..07bd0f61fe--- /dev/null+++ b/examples/plugins/deploy-sentinel/README.md@@ -0,0 +1,108 @@+# Deploy Sentinel++A production-incident plugin. It correlates an incident issue with recent+deploys, lets an agent file a rollback request under the team's own rules, pages+on-call when an incident is filed, and adopts the team's existing metrics MCP+server.++It exists because the other examples in this directory each demonstrate one+thing. This one is the shape of a plugin somebody would actually write: four+triggers, both transports, real business rules that refuse things, and a skill+that teaches an agent when to use any of it.++## What it contributes++| Contribution | Kind | What it demonstrates |+| --- | --- | --- |+| `incident-response` | skill resource | A `SKILL.md` becomes an ordinary workspace skill. Uninstall removes it. |+| `correlate_deploys` | hook, `agent` + `manual` + `ui` | One hook, three callers. The agent gets a tool; a person gets a button; the panel gets a function. |+| `request_rollback` | hook, `agent` + `manual` | A write action that **refuses**: too old, or no written reason. |+| `page_oncall` | hook, `event` | Fires on `issue.created` / `issue.status_changed`. Never blocks anything. |+| `metrics` | hook, `mcp` transport | Adopts an external MCP server's tools, subject to admin approval. |+| `incident` | `issue_panel` surface | The human view, in a sandboxed iframe with no credential. |++## The part worth copying++**`request_rollback` says no.** It refuses a deploy past the configured window,+and it refuses a reason shorter than 20 characters. An agent that has to write+evidence before it can file a change request produces better change requests —+and the refusal text explains why, so the agent can act on it rather than retry+blindly. Hook handlers that only ever succeed are the easy case; this one is the+useful one.++**`correlate_deploys` reports "nothing changed" as an answer**, not as an empty+list. The skill then tells the agent that an empty result means it should stop+looking at deploys. A tool that returns `[]` and a tool that says "no deploys in+this window, this is unlikely to be a deploy" cost the same to write and behave+very differently in an agent's hands.++**The skill and the hooks are designed together.** `SKILL.md` names the tools and+says what order to use them in. Neither half works as well alone.++## Running it locally++Two servers, both the plugin author's own. Multica never runs either.++Both serve HTTPS, because a hook's transport URL must be an `https://` URL or+the manifest will not install. Make a certificate once:++```bash+openssl req -x509 -newkey rsa:2048 -nodes -days 365 \+ -keyout dev-key.pem -out dev-cert.pem \+ -subj "/CN=127.0.0.1" -addext "subjectAltName=IP:127.0.0.1"+```++```bash+# The hook endpoint. The signing secret is the whsec_… shown once when you+# issued the plugin's token in workspace settings.+MULTICA_SIGNING_SECRET=whsec_... node server/handler.mjs # :8788++# The MCP server behind the `metrics` hook.+METRICS_TOKEN=metrics-dev-token node server/metrics-mcp.mjs # :8789+```++Both read `TLS_CERT` / `TLS_KEY`, defaulting to `dev-cert.pem` / `dev-key.pem`+in the working directory.++Then point Multica at them. Both endpoints are on loopback, which the outbound+guard refuses by design, so name them explicitly:++```bash+export MULTICA_PLUGIN_DIR=examples/plugins+export MULTICA_PLUGIN_DEV_ORIGINS=https://127.0.0.1:8788,https://127.0.0.1:8789+export MULTICA_PLUGIN_DEV_CA=/path/to/your-dev-ca.pem+```++Install it as `local:deploy-sentinel`, fill in the config form, then open the+`metrics` approval panel and tick the tools you want agents to reach. Nothing+under `metrics` is callable until you do — that is the whole difference between+the `mcp` transport and an `http` hook.++Both endpoints must be HTTPS even locally: the manifest validator requires it,+and `MULTICA_PLUGIN_DEV_CA` is how you get a self-signed certificate trusted.+The dev switches change *which* certificate is trusted and *whether the address+must be public*. They never disable verification, and they never widen the+`net:` scopes — a hook still cannot reach a host the administrator did not+approve.++## Try breaking it++- Ask an agent to roll back `d-4802`. It is 380 minutes old; the plugin refuses+ and explains why.+- Ask for a rollback with the reason "broken". Refused — too short.+- Add a tool to `server/metrics-mcp.mjs` and reopen the approval panel. It+ appears unapproved, and agents cannot call it until somebody ticks it.+- Change an approved tool's `inputSchema` and restart. The agent's task starts+ fine, but that connection is refused: the schema no longer matches what was+ approved.++## Tested++`server/internal/handler/plugin_example_test.go` installs **this manifest**,+not a copy, and drives it: the skill lands in the skill table, the agent tool+list contains exactly the hooks that declare the `agent` trigger, an agent hook+call goes out signed and comes back, and the `metrics` tools are discovered,+refused before approval, and pinned by schema digest after it.++The `.mjs` files are what you run by hand. The test uses Go servers that answer+the same contract, so CI does not need node.diff --git a/examples/plugins/deploy-sentinel/multica.plugin.json b/examples/plugins/deploy-sentinel/multica.plugin.jsonnew file mode 100644index 0000000000..776f8400a4--- /dev/null+++ b/examples/plugins/deploy-sentinel/multica.plugin.json@@ -0,0 +1,118 @@+{+ "manifest_version": 1,+ "key": "com.example.deploy-sentinel",+ "name": "Deploy Sentinel",+ "description": "Correlates production incidents with recent deploys, and lets an agent request a rollback under the team's own rules.",+ "version": "1.0.0",+ "author": { "name": "Example Infra Team", "url": "https://example.com" },++ "scopes": [+ "issues:read",+ "issues:write",+ "comments:read",+ "comments:write",+ "storage:workspace",+ "net:sentinel.example.com",+ "net:metrics.example.com"+ ],++ "config": {+ "service_prefix": {+ "type": "string",+ "label": "Service name prefix",+ "required": true+ },+ "rollback_window_minutes": {+ "type": "number",+ "label": "How recent a deploy must be to be rollback-eligible",+ "required": true+ },+ "require_incident_label": {+ "type": "bool",+ "label": "Only correlate issues labelled as incidents"+ },+ "environment": {+ "type": "enum",+ "label": "Environment",+ "options": ["production", "staging"],+ "required": true+ },+ "sentinel_token": {+ "type": "secret",+ "label": "Deploy Sentinel API token",+ "required": true+ },+ "metrics_credential": {+ "type": "secret",+ "label": "Metrics MCP server token"+ }+ },++ "contributes": {+ "surfaces": [+ {+ "key": "incident",+ "type": "issue_panel",+ "name": "Deploy Sentinel",+ "entry": "ui/main.js",+ "platforms": ["web", "desktop"]+ }+ ],++ "hooks": [+ {+ "key": "correlate_deploys",+ "name": "Correlate recent deploys",+ "description": "Given a service and a time window, list the deploys that landed in that window with their commit, author and blast radius. Call this first when investigating a production incident: it is the fastest way to find out what changed. Returns an empty list when nothing deployed, which is itself a useful answer.",+ "input_schema": {+ "type": "object",+ "required": ["service"],+ "properties": {+ "service": { "type": "string", "description": "Service name, without the configured prefix." },+ "window_minutes": { "type": "number", "description": "How far back to look. Defaults to 120." }+ }+ },+ "triggers": ["agent", "manual", "ui"],+ "transport": { "type": "http", "url": "https://sentinel.example.com/hooks/correlate" },+ "timeout_ms": 15000+ },+ {+ "key": "request_rollback",+ "name": "Request a rollback",+ "description": "Open a rollback change request for one deploy. This does NOT roll anything back by itself: it files the request and returns a change id for a human to approve. Refuses deploys older than the configured window, and requires a written reason that goes into the change record.",+ "input_schema": {+ "type": "object",+ "required": ["deploy_id", "reason"],+ "properties": {+ "deploy_id": { "type": "string" },+ "reason": { "type": "string", "description": "Why this deploy is suspected. Goes into the change record verbatim." }+ }+ },+ "triggers": ["agent", "manual"],+ "transport": { "type": "http", "url": "https://sentinel.example.com/hooks/rollback" },+ "timeout_ms": 20000+ },+ {+ "key": "page_oncall",+ "name": "Page the on-call engineer",+ "description": "Fires when an issue is created or changes status, so a new incident reaches a human without anybody watching the board.",+ "triggers": ["event"],+ "events": ["issue.created", "issue.status_changed"],+ "transport": { "type": "http", "url": "https://sentinel.example.com/hooks/page" },+ "timeout_ms": 10000+ },+ {+ "key": "metrics",+ "name": "Metrics queries",+ "description": "Tools from the team's own metrics MCP server: time series, alert history, and service dependency lookups.",+ "triggers": ["agent"],+ "transport": { "type": "mcp", "url": "https://metrics.example.com/mcp" },+ "timeout_ms": 30000+ }+ ],++ "resources": [+ { "type": "skill", "key": "incident-response", "entry": "skills/incident-response/SKILL.md" }+ ]+ }+}diff --git a/examples/plugins/deploy-sentinel/server/handler.mjs b/examples/plugins/deploy-sentinel/server/handler.mjsnew file mode 100644index 0000000000..fec78dde25--- /dev/null+++ b/examples/plugins/deploy-sentinel/server/handler.mjs@@ -0,0 +1,227 @@+// Deploy Sentinel's own server. Multica never runs this — the plugin author does.+//+// Everything a real hook backend has to get right is here and nowhere else:+// verifying the signature, refusing a replay, applying the team's own rules, and+// using the per-invocation callback token to write back to the issue.+//+// node server/handler.mjs+//+// Env: MULTICA_SIGNING_SECRET (the whsec_… shown once when the token was issued)+// PORT (default 8788)++import { createServer } from "node:https";+import { readFileSync } from "node:fs";+import { createHmac, timingSafeEqual } from "node:crypto";++// HTTPS, not HTTP. A hook's transport URL must be an https:// URL or the+// manifest will not install, and MULTICA_PLUGIN_DEV_CA only changes WHICH+// certificate Multica trusts — it never turns verification off. Generate one:+//+// openssl req -x509 -newkey rsa:2048 -nodes -days 365 \+// -keyout dev-key.pem -out dev-cert.pem \+// -subj "/CN=127.0.0.1" -addext "subjectAltName=IP:127.0.0.1"+//+// then point MULTICA_PLUGIN_DEV_CA at dev-cert.pem.+function tlsOptions() {+ const cert = process.env.TLS_CERT ?? "dev-cert.pem";+ const key = process.env.TLS_KEY ?? "dev-key.pem";+ try {+ return { cert: readFileSync(cert), key: readFileSync(key) };+ } catch (error) {+ console.error(`Could not read ${cert} / ${key}: ${error.message}`);+ console.error("See the README for the openssl one-liner that generates them.");+ process.exit(1);+ }+}++const PORT = Number(process.env.PORT ?? 8788);+const SIGNING_SECRET = process.env.MULTICA_SIGNING_SECRET ?? "";+const REPLAY_WINDOW_SECONDS = 300;++// Stand-in for the deploy system this plugin would really talk to. Deploy ids+// are stable so the README's walkthrough is reproducible.+const DEPLOYS = [+ { id: "d-4821", service: "checkout-api", minutes_ago: 4, commit: "9f2c1ab", author: "rivera", blast_radius: "all checkout traffic", touches: ["retry path", "timeout config"] },+ { id: "d-4820", service: "checkout-api", minutes_ago: 51, commit: "1de77c0", author: "okafor", blast_radius: "checkout traffic in EU", touches: ["currency formatting"] },+ { id: "d-4816", service: "search-api", minutes_ago: 92, commit: "aa30f41", author: "rivera", blast_radius: "search suggestions", touches: ["index warmup"] },+ { id: "d-4802", service: "checkout-api", minutes_ago: 380, commit: "77b9e2d", author: "chen", blast_radius: "all checkout traffic", touches: ["payment provider client"] },+];++const filedRollbacks = new Map();++function verifySignature(rawBody, signature, timestamp) {+ if (!SIGNING_SECRET) return { ok: false, reason: "server has no signing secret configured" };+ if (!signature || !timestamp) return { ok: false, reason: "missing signature headers" };++ // Reject a replay before spending time on the comparison. Multica signs+ // timestamp + body precisely so an old, validly-signed request cannot be+ // resent later.+ const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));+ if (!Number.isFinite(age) || age > REPLAY_WINDOW_SECONDS) {+ return { ok: false, reason: "timestamp outside the replay window" };+ }++ const expected = createHmac("sha256", SIGNING_SECRET).update(`${timestamp}.${rawBody}`).digest("hex");+ const provided = Buffer.from(signature, "utf8");+ const computed = Buffer.from(expected, "utf8");+ // Length check first: timingSafeEqual throws on a mismatch rather than+ // returning false, and the length is not the secret.+ if (provided.length !== computed.length || !timingSafeEqual(provided, computed)) {+ return { ok: false, reason: "signature mismatch" };+ }+ return { ok: true };+}++// The callback token is scoped to THIS invocation and is revoked the moment the+// hook returns, so anything the handler wants to write has to be written before+// it replies. That constraint is the reason this is awaited, not fired off.+async function commentOnIssue(callback, issueId, body) {+ if (!callback?.token || !callback?.base_url || !issueId) return;+ try {+ const response = await fetch(`${callback.base_url}/api/v1/plugin/issues/${issueId}/comments`, {+ method: "POST",+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${callback.token}` },+ body: JSON.stringify({ body }),+ });+ if (!response.ok) {+ console.warn(`callback comment failed: ${response.status} ${await response.text()}`);+ }+ } catch (error) {+ // A failed write-back must not fail the hook: the agent still gets its+ // answer, and a missing comment is recoverable where a failed tool is not.+ console.warn("callback comment error:", error.message);+ }+}++function correlateDeploys(input, config) {+ const windowMinutes = Number(input.window_minutes ?? 120);+ const service = `${config.service_prefix ?? ""}${input.service ?? ""}`;++ const matches = DEPLOYS+ .filter((deploy) => `${config.service_prefix ?? ""}${deploy.service}` === service)+ .filter((deploy) => deploy.minutes_ago <= windowMinutes)+ .sort((a, b) => a.minutes_ago - b.minutes_ago);++ return {+ service,+ window_minutes: windowMinutes,+ deploy_count: matches.length,+ deploys: matches,+ // Said explicitly rather than left for the agent to infer from an empty+ // array. "Nothing deployed" is a real finding and the skill tells the agent+ // to report it rather than keep digging.+ summary: matches.length === 0+ ? `No deploys to ${service} in the last ${windowMinutes} minutes. This is unlikely to be a deploy.`+ : `${matches.length} deploy(s) to ${service} in the last ${windowMinutes} minutes; most recent is ${matches[0].id} (${matches[0].minutes_ago}m ago, ${matches[0].commit} by ${matches[0].author}).`,+ };+}++function requestRollback(input, config) {+ const deploy = DEPLOYS.find((entry) => entry.id === input.deploy_id);+ if (!deploy) {+ return { status: "rejected", reason: `Unknown deploy ${input.deploy_id}.` };+ }++ const reason = String(input.reason ?? "").trim();+ if (reason.length < 20) {+ // The approver reads this at 3am; a one-word reason wastes their time.+ return {+ status: "rejected",+ reason: "A rollback request needs a written reason (at least 20 characters) describing the evidence, not the conclusion.",+ };+ }++ const windowMinutes = Number(config.rollback_window_minutes ?? 60);+ if (deploy.minutes_ago > windowMinutes) {+ return {+ status: "rejected",+ reason: `Deploy ${deploy.id} landed ${deploy.minutes_ago} minutes ago, past the ${windowMinutes}-minute rollback window. Past that point a fix forward is usually safer, and it needs a human deciding.`,+ };+ }++ const changeId = `chg-${String(filedRollbacks.size + 1).padStart(4, "0")}`;+ filedRollbacks.set(changeId, { deploy: deploy.id, reason });+ return {+ status: "filed",+ change_id: changeId,+ deploy_id: deploy.id,+ environment: config.environment ?? "production",+ // Stated so the agent does not report the incident as handled.+ next_step: "A human must approve this change request. Nothing has been rolled back yet.",+ };+}++const server = createServer(tlsOptions(), async (req, res) => {+ const chunks = [];+ for await (const chunk of req) chunks.push(chunk);+ const rawBody = Buffer.concat(chunks).toString("utf8");++ const reply = (status, payload) => {+ res.writeHead(status, { "Content-Type": "application/json" });+ res.end(JSON.stringify(payload));+ };++ const verified = verifySignature(+ rawBody,+ req.headers["x-multica-signature"],+ req.headers["x-multica-timestamp"],+ );+ if (!verified.ok) {+ console.warn(`refused ${req.url}: ${verified.reason}`);+ return reply(401, { error: verified.reason });+ }++ let payload;+ try {+ payload = JSON.parse(rawBody || "{}");+ } catch {+ return reply(400, { error: "body is not valid JSON" });+ }++ const { hook_key: hookKey, trigger, input = {}, config = {}, callback, issue_id: issueId } = payload;+ console.log(`${hookKey} via ${trigger}`);++ switch (hookKey) {+ case "correlate_deploys": {+ const result = correlateDeploys(input, config);+ // A ui/manual click is a person asking; leave the answer where they and+ // their colleagues will see it. An agent call already returns to the+ // agent, which will write its own account of what it found.+ if (trigger === "ui" || trigger === "manual") {+ await commentOnIssue(callback, issueId, `**Deploy Sentinel** — ${result.summary}`);+ }+ return reply(200, result);+ }++ case "request_rollback": {+ const result = requestRollback(input, config);+ if (result.status === "filed") {+ await commentOnIssue(+ callback,+ issueId,+ `**Deploy Sentinel** filed rollback ${result.change_id} for deploy ${result.deploy_id}.\n\n> ${input.reason}\n\nAwaiting human approval — nothing has been rolled back.`,+ );+ }+ return reply(200, result);+ }++ case "page_oncall": {+ // An event hook's response is discarded, so there is nothing to return+ // that anybody reads. Acknowledge fast and do the work; blocking here+ // would hold a Multica worker for no benefit.+ const issue = payload.event?.issue ?? {};+ console.log(`paging on-call for ${payload.event?.type}: ${issue.title ?? issueId}`);+ return reply(202, { acknowledged: true });+ }++ default:+ return reply(404, { error: `unknown hook ${hookKey}` });+ }+});++server.listen(PORT, () => {+ console.log(`Deploy Sentinel listening on https://127.0.0.1:${PORT}`);+ if (!SIGNING_SECRET) {+ console.warn("MULTICA_SIGNING_SECRET is not set — every request will be refused.");+ }+});diff --git a/examples/plugins/deploy-sentinel/server/metrics-mcp.mjs b/examples/plugins/deploy-sentinel/server/metrics-mcp.mjsnew file mode 100644index 0000000000..a9a9af00bf--- /dev/null+++ b/examples/plugins/deploy-sentinel/server/metrics-mcp.mjs@@ -0,0 +1,147 @@+// The metrics MCP server behind the `metrics` hook.+//+// This is the case the `mcp` transport exists for: the team already runs an MCP+// server and does not want to re-expose it as HTTP hooks. Multica adopts its+// tools — but only the ones an administrator approved, pinned by schema digest.+//+// node server/metrics-mcp.mjs+//+// Env: METRICS_TOKEN (matched against the `metrics_credential` plugin secret)+// PORT (default 8789)+//+// Try adding a tool below and re-opening the approval panel: the new tool shows+// up as unapproved and agents cannot call it until somebody ticks it.++import { createServer } from "node:https";+import { readFileSync } from "node:fs";++// HTTPS, not HTTP. A hook's transport URL must be an https:// URL or the+// manifest will not install, and MULTICA_PLUGIN_DEV_CA only changes WHICH+// certificate Multica trusts — it never turns verification off. Generate one:+//+// openssl req -x509 -newkey rsa:2048 -nodes -days 365 \+// -keyout dev-key.pem -out dev-cert.pem \+// -subj "/CN=127.0.0.1" -addext "subjectAltName=IP:127.0.0.1"+//+// then point MULTICA_PLUGIN_DEV_CA at dev-cert.pem.+function tlsOptions() {+ const cert = process.env.TLS_CERT ?? "dev-cert.pem";+ const key = process.env.TLS_KEY ?? "dev-key.pem";+ try {+ return { cert: readFileSync(cert), key: readFileSync(key) };+ } catch (error) {+ console.error(`Could not read ${cert} / ${key}: ${error.message}`);+ console.error("See the README for the openssl one-liner that generates them.");+ process.exit(1);+ }+}++const PORT = Number(process.env.PORT ?? 8789);+const TOKEN = process.env.METRICS_TOKEN ?? "metrics-dev-token";++const TOOLS = [+ {+ name: "query_timeseries",+ description: "Query a metric over a time window. Returns datapoints at the coarsest resolution that covers the window.",+ inputSchema: {+ type: "object",+ required: ["metric", "window_minutes"],+ properties: {+ metric: { type: "string", description: "e.g. checkout-api.error_rate" },+ window_minutes: { type: "number" },+ },+ },+ },+ {+ name: "list_alerts",+ description: "Alerts that fired in a window, most recent first, with the threshold each one crossed.",+ inputSchema: {+ type: "object",+ properties: { window_minutes: { type: "number" }, service: { type: "string" } },+ },+ },+ {+ name: "service_dependencies",+ description: "Which services this one calls and which call it. Useful for deciding whether an error is originating here or arriving from upstream.",+ inputSchema: {+ type: "object",+ required: ["service"],+ properties: { service: { type: "string" } },+ },+ },+];++const SERIES = {+ "checkout-api.error_rate": [+ { minutes_ago: 6, value: 0.002 }, { minutes_ago: 4, value: 0.058 },+ { minutes_ago: 2, value: 0.061 }, { minutes_ago: 0, value: 0.064 },+ ],+};++function callTool(name, args) {+ switch (name) {+ case "query_timeseries": {+ const points = SERIES[args.metric] ?? [];+ const within = points.filter((point) => point.minutes_ago <= Number(args.window_minutes ?? 60));+ return within.length === 0+ ? `No datapoints for ${args.metric} in the last ${args.window_minutes} minutes.`+ : `${args.metric}: ${within.map((p) => `${p.minutes_ago}m ago = ${p.value}`).join(", ")}`;+ }+ case "list_alerts":+ return "ALERT checkout-api.error_rate crossed 0.05 (fired 4m ago, still firing).";+ case "service_dependencies":+ return `${args.service} calls: payments-api, inventory-api. Called by: web, mobile-bff.`;+ default:+ return null;+ }+}++createServer(tlsOptions(), async (req, res) => {+ const chunks = [];+ for await (const chunk of req) chunks.push(chunk);++ res.setHeader("Content-Type", "application/json");+ if (req.headers.authorization !== `Bearer ${TOKEN}`) {+ res.writeHead(401);+ return res.end(JSON.stringify({ error: "credential rejected" }));+ }++ let request;+ try {+ request = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");+ } catch {+ res.writeHead(400);+ return res.end();+ }++ const send = (result) => res.end(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }));++ switch (request.method) {+ case "initialize":+ return send({+ protocolVersion: "2025-03-26",+ capabilities: { tools: {} },+ serverInfo: { name: "deploy-sentinel-metrics", version: "1.0.0" },+ });+ case "notifications/initialized":+ res.writeHead(202);+ return res.end();+ case "tools/list":+ return send({ tools: TOOLS });+ case "tools/call": {+ const text = callTool(request.params?.name, request.params?.arguments ?? {});+ if (text === null) {+ return res.end(JSON.stringify({+ jsonrpc: "2.0", id: request.id,+ error: { code: -32602, message: `unknown tool ${request.params?.name}` },+ }));+ }+ return send({ content: [{ type: "text", text }] });+ }+ default:+ return res.end(JSON.stringify({+ jsonrpc: "2.0", id: request.id,+ error: { code: -32601, message: `method not found: ${request.method}` },+ }));+ }+}).listen(PORT, () => console.log(`metrics MCP server on https://127.0.0.1:${PORT}`));diff --git a/examples/plugins/deploy-sentinel/skills/incident-response/SKILL.md b/examples/plugins/deploy-sentinel/skills/incident-response/SKILL.mdnew file mode 100644index 0000000000..93951246ad--- /dev/null+++ b/examples/plugins/deploy-sentinel/skills/incident-response/SKILL.md@@ -0,0 +1,59 @@+---+name: incident-response+description: How this team handles a production incident issue — what to establish before proposing a fix, and what an agent may and may not do on its own.+---++# Incident response++An incident issue is not a bug report. The goal is to stop the bleeding first and+explain it second, and those two are frequently in tension.++## Establish, in this order++1. **Blast radius.** Who is affected and how badly. An error rate that doubled+ from 0.01% is not the same incident as one that doubled from 4%.+2. **When it started.** Get a timestamp before you get a theory. The first+ timestamp people offer is usually when somebody *noticed*, not when it began.+3. **What changed.** Call `correlate_deploys` with the service and a window that+ starts before the timestamp from step 2. An empty result is informative: it+ means this is probably not a deploy, and you should stop looking there.++Do not skip to step 3. A deploy that landed in the window is not automatically+the cause, and the fastest way to waste an hour is to roll back the first+plausible change and watch the incident continue.++## Rollback++`request_rollback` files a change request. It does not roll anything back — a+human approves it. So filing one is cheap, and you should file it as soon as you+have a specific deploy and a reason, rather than waiting until you are certain.++The `reason` you write goes into the change record verbatim and is what the+approver reads at 3am. Write the evidence, not the conclusion:++- Good: "error rate on checkout-api went 0.2% → 6% within 90s of deploy d-4821;+ no other deploy in the window; the diff touches the retry path."+- Bad: "this deploy broke checkout."++Deploys older than the configured rollback window are refused. That is+deliberate: past that point a rollback is usually more dangerous than a fix+forward, and it needs a human deciding, not a tool call.++## What to write on the issue++Update the issue as you go rather than at the end. Someone else may be reading+it to decide whether to escalate, and an issue that goes quiet for twenty+minutes reads as "nobody is on this".++Keep the timeline in the issue description and the reasoning in comments. The+description is what someone reads six months later during a postmortem; the+comments are what your colleagues read right now.++## What not to do++- Do not change issue status to done because the error rate recovered. Recovery+ and resolution are different; an incident stays open until somebody explains+ it.+- Do not close the loop silently. If you correlated deploys and found nothing,+ say so on the issue — that is a real result and it stops the next person+ repeating it.diff --git a/examples/plugins/deploy-sentinel/ui/main.js b/examples/plugins/deploy-sentinel/ui/main.jsnew file mode 100644index 0000000000..951a2c0a5c--- /dev/null+++ b/examples/plugins/deploy-sentinel/ui/main.js@@ -0,0 +1,85 @@+// The human side of Deploy Sentinel: an issue panel that answers "what changed"+// without making anybody leave the issue.+//+// The host renders the surrounding document and injects its own theme, so this+// file is only the behaviour. It runs in a sandboxed iframe with an opaque+// origin: no host cookies, no host storage, and no credential of any kind. Every+// call below goes over the bridge, where the host re-issues it as the signed-in+// user and checks the scopes this plugin was granted.++import { multica } from "https://esm.sh/@multica/plugin-sdk@1";++const root = document.getElementById("root");++function render(html) {+ root.innerHTML = html;+}++function escapeHTML(value) {+ return String(value).replace(/[&<>"']/g, (character) => ({+ "&": "&", "<": "<", ">": ">", '"': """, "'": "'",+ })[character]);+}++function deployRow(deploy) {+ return `+ <li class="deploy">+ <div class="deploy-head">+ <code>${escapeHTML(deploy.id)}</code>+ <span class="muted">${escapeHTML(deploy.minutes_ago)}m ago · ${escapeHTML(deploy.author)}</span>+ </div>+ <div class="muted">${escapeHTML(deploy.commit)} — ${escapeHTML(deploy.blast_radius)}</div>+ <button data-rollback="${escapeHTML(deploy.id)}">Request rollback</button>+ </li>`;+}++async function correlate() {+ render(`<p class="muted">Looking for recent deploys…</p>`);+ try {+ const issue = await multica.issue.get();+ // The service name is a workspace-level setting rather than something+ // typed per issue: everyone investigating the same service should get the+ // same answer.+ const service = (await multica.storage.workspace.get("default_service")) ?? "checkout-api";++ const result = await multica.hooks.invoke("correlate_deploys", {+ service,+ window_minutes: 120,+ });++ if (!result?.deploys?.length) {+ render(`<p>${escapeHTML(result?.summary ?? "No deploys found.")}</p>`);+ return;+ }+ render(`+ <p>${escapeHTML(result.summary)}</p>+ <ul class="deploys">${result.deploys.map(deployRow).join("")}</ul>+ <p class="muted">Issue: ${escapeHTML(issue?.title ?? "")}</p>+ `);+ } catch (error) {+ // A failing hook is the plugin author's own server being down. Say that,+ // rather than showing an empty panel that reads like "nothing deployed".+ render(`<p class="error">Deploy Sentinel could not reach its backend: ${escapeHTML(error.message)}</p>`);+ }+}++root.addEventListener("click", async (event) => {+ const deployId = event.target?.dataset?.rollback;+ if (!deployId) return;++ const reason = prompt("Why is this deploy suspected? The approver reads this — write the evidence, not the conclusion.");+ if (!reason) return;++ event.target.disabled = true;+ try {+ const result = await multica.hooks.invoke("request_rollback", { deploy_id: deployId, reason });+ render(result.status === "filed"+ ? `<p>Filed <code>${escapeHTML(result.change_id)}</code>. ${escapeHTML(result.next_step)}</p>`+ : `<p class="error">${escapeHTML(result.reason)}</p>`);+ } catch (error) {+ render(`<p class="error">${escapeHTML(error.message)}</p>`);+ }+});++multica.ui.resize(360);+correlate();diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex a0548eb512..5f1115e5bb 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -152,6 +152,7 @@ import type {PluginInstallation,PluginInstallationListResponse,PluginInvocation,+ PluginMCPTool,PluginPreview,PluginTokenIssue,PluginPreviewRequest,@@ -405,6 +406,7 @@ import {PluginHookResultSchema,PluginInstallationListResponseSchema,PluginInvocationListSchema,+ PluginMCPToolListSchema,PluginTokenIssueSchema,PluginInstallationSchema,PluginPreviewSchema,@@ -2561,6 +2563,45 @@ export class ApiClient {await this.fetch(`/api/workspaces/${workspaceId}/plugins/${installationId}/token`, { method: "DELETE" });}+ /**+ * Lists what an `mcp`-transport hook's server currently offers.+ *+ * Read-only: discovering a tool adopts nothing. approvePluginMCPTools is the+ * grant, which is the difference from an `http` hook — that one declares a+ * single endpoint in a manifest an administrator already read, while an MCP+ * server decides its own tool list at runtime and can change it later.+ */+ async listPluginMCPTools(workspaceId: string, installationId: string, hookKey: string): Promise<PluginMCPTool[]> {+ const raw = await this.fetch<unknown>(+ `/api/workspaces/${workspaceId}/plugins/${installationId}/mcp/${encodeURIComponent(hookKey)}/tools`,+ );+ return parseWithFallback(raw, PluginMCPToolListSchema, { tools: [] }, {+ endpoint: "GET /api/workspaces/{id}/plugins/{installationId}/mcp/{hookKey}/tools",+ }).tools;+ }++ /**+ * Pins the approved tool set for one hook.+ *+ * `tools` is the COMPLETE set, not a delta — removing one is the same request+ * shape as adding one, so there is no way to think you revoked something and+ * have it stay. An empty array withdraws the hook entirely.+ */+ async approvePluginMCPTools(+ workspaceId: string,+ installationId: string,+ hookKey: string,+ tools: string[],+ ): Promise<PluginInstallation> {+ const raw = await this.fetch<unknown>(+ `/api/workspaces/${workspaceId}/plugins/${installationId}/mcp/${encodeURIComponent(hookKey)}/tools`,+ { method: "PUT", body: JSON.stringify({ tools }) },+ );+ return parseWithFallback(raw, PluginInstallationSchema, EMPTY_PLUGIN_INSTALLATION, {+ endpoint: "PUT /api/workspaces/{id}/plugins/{installationId}/mcp/{hookKey}/tools",+ });+ }+async uninstallPlugin(workspaceId: string, installationId: string): Promise<void> {await this.fetch(`/api/workspaces/${workspaceId}/plugins/${installationId}`, {method: "DELETE",diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 9788ba840e..ff54080382 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -56,6 +56,7 @@ import {UserSchema,PluginInstallationSchema,PluginInstallationListResponseSchema,+ PluginMCPToolListSchema,PluginPreviewSchema,EMPTY_PLUGIN_INSTALLATION_LIST,EMPTY_PLUGIN_PREVIEW,@@ -1606,6 +1607,22 @@ describe("Plugin schemas", () => {expect(parsed.scopes).toEqual([]);});+ it("degrades a malformed MCP tool list to empty rather than showing tools as approved", () => {+ const parsed = parseWithFallback({ tools: "search" }, PluginMCPToolListSchema, { tools: [] }, {+ endpoint: "GET /api/workspaces/{id}/plugins/{installationId}/mcp/{hookKey}/tools",+ });+ expect(parsed.tools).toEqual([]);+ });++ // The dangerous direction is one-sided: a response missing `approved` must+ // read as NOT approved. The opposite default would render an unpinned tool+ // with a checked box, and the administrator's next save would pin it.+ it("treats a tool with no approval field as unapproved", () => {+ const parsed = PluginMCPToolListSchema.parse({ tools: [{ name: "search" }] });+ expect(parsed.tools[0]?.approved).toBe(false);+ expect(parsed.tools[0]?.drifted).toBe(false);+ });+it("parses a preview that reports an upgrade adding new scopes", () => {const parsed = PluginPreviewSchema.parse({manifest: { key: "com.example.hello", name: "Hello", version: "2.0.0", author: { name: "example" } },diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 5b7791d308..5791183d7c 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -202,6 +202,25 @@ export const PluginTokenIssueSchema = z.object({signing_secret: z.string().default(""),}).loose();+/**+ * Discovered tools for one `mcp`-transport hook.+ *+ * Defaults matter here in the usual direction: an unparseable response yields+ * an EMPTY list and nothing approved, so a drifted backend cannot make the UI+ * render a tool as already-approved.+ */+export const PluginMCPToolSchema = z.object({+ name: z.string().default(""),+ description: z.string().default(""),+ schema_digest: z.string().default(""),+ approved: z.boolean().default(false),+ drifted: z.boolean().default(false),+}).loose();++export const PluginMCPToolListSchema = z.object({+ tools: z.array(PluginMCPToolSchema).default([]),+}).loose();+export const PluginManifestSummarySchema = z.object({key: z.string().default(""),name: z.string().default(""),diff --git a/packages/core/plugins/mutations.ts b/packages/core/plugins/mutations.tsindex 1d3d9bbeca..d26ad6cb0b 100644--- a/packages/core/plugins/mutations.ts+++ b/packages/core/plugins/mutations.ts@@ -45,6 +45,21 @@ export function useSetPluginEnabled(wsId: string) {});}+/**+ * Pins the approved tool set for one `mcp` hook.+ *+ * `tools` is the complete set the administrator wants approved, never a delta —+ * unchecking one and saving is what revokes it. An empty array withdraws the+ * hook, and the next task claim stops offering it to agents.+ */+export function useApprovePluginMCPTools(wsId: string, installationId: string, hookKey: string) {+ const invalidate = useInvalidatePlugins(wsId);+ return useMutation({+ mutationFn: (tools: string[]) => api.approvePluginMCPTools(wsId, installationId, hookKey, tools),+ onSettled: invalidate,+ });+}+export function useUninstallPlugin(wsId: string) {const invalidate = useInvalidatePlugins(wsId);return useMutation({diff --git a/packages/core/plugins/queries.ts b/packages/core/plugins/queries.tsindex da4d3001aa..c3c88ffb7c 100644--- a/packages/core/plugins/queries.ts+++ b/packages/core/plugins/queries.ts@@ -28,3 +28,21 @@ export function pluginInvocationsOptions(wsId: string, installationId: string) {staleTime: 5_000,});}++/**+ * What an `mcp`-transport hook's server currently offers.+ *+ * Reaches the plugin author's MCP server on every read, which is why it is not+ * prefetched anywhere: it runs when an administrator opens the approval panel+ * and asks. `staleTime` is short because the reason for opening it is to see+ * the current tool list, and drift is exactly what it exists to surface.+ */+export function pluginMCPToolsOptions(wsId: string, installationId: string, hookKey: string) {+ return queryOptions({+ queryKey: [...pluginKeys.all(wsId), installationId, "mcp", hookKey] as const,+ queryFn: () => api.listPluginMCPTools(wsId, installationId, hookKey),+ enabled: wsId.length > 0 && installationId.length > 0 && hookKey.length > 0,+ staleTime: 5_000,+ retry: false,+ });+}diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 164acd6cb0..f2686688eb 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -101,6 +101,7 @@ export type {PluginConfigRequest,PluginHookResult,PluginInvocation,+ PluginMCPTool,PluginTokenIssue,} from "./plugin";export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread } from "./inbox";diff --git a/packages/core/types/plugin.ts b/packages/core/types/plugin.tsindex d6559a120d..61e59175d9 100644--- a/packages/core/types/plugin.ts+++ b/packages/core/types/plugin.ts@@ -144,3 +144,19 @@ export interface PluginTokenIssue {token: string;signing_secret: string;}++/**+ * One tool an `mcp`-transport hook's server currently offers.+ *+ * `approved` is the administrator's pin. `drifted` means the tool IS approved+ * but its schema no longer matches what was approved — surfaced rather than+ * silently re-approved, because the administrator approved a specific shape and+ * a changed one is a new decision.+ */+export interface PluginMCPTool {+ name: string;+ description: string;+ schema_digest: string;+ approved: boolean;+ drifted: boolean;+}diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 67b192d11b..34ab61629e 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -392,7 +392,17 @@"unknown": "Unrecognized access — do not install"},"hook_circuit_open": "Hook delivery has stopped after repeated failures.",- "hook_recent_failures": "{{count}} recent hook calls failed."+ "hook_recent_failures": "{{count}} recent hook calls failed.",+ "mcp": {+ "badge": "MCP",+ "description": "This hook adopts tools from the Plugin author's own MCP server. Approve the ones agents may call — a tool that appears later is not adopted until you approve it.",+ "loading": "Loading tools",+ "unreachable": "Could not reach the Plugin's MCP server.",+ "empty": "This MCP server currently offers no tools.",+ "drifted": "Schema changed",+ "save": "Save approvals",+ "approved": "Approved tools updated."+ }},"properties": {"title": "Properties",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 5797505dad..e5a15cab79 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -392,7 +392,17 @@"unknown": "認識できない権限です — インストールしないでください"},"hook_circuit_open": "連続失敗のためフックの配信を停止しました。",- "hook_recent_failures": "最近 {{count}} 件のフック呼び出しが失敗しました。"+ "hook_recent_failures": "最近 {{count}} 件のフック呼び出しが失敗しました。",+ "mcp": {+ "badge": "MCP",+ "description": "このフックはプラグイン作者自身の MCP サーバーのツールを採用します。エージェントが呼び出せるツールを承認してください。後から追加されたツールは、承認するまで採用されません。",+ "loading": "ツールを読み込み中",+ "unreachable": "プラグインの MCP サーバーに接続できませんでした。",+ "empty": "この MCP サーバーは現在ツールを提供していません。",+ "drifted": "スキーマが変更されました",+ "save": "承認を保存",+ "approved": "承認済みツールを更新しました。"+ }},"properties": {"title": "プロパティ",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex c68e60fe5e..4d3bfd095a 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -392,7 +392,17 @@"unknown": "알 수 없는 권한 — 설치하지 마세요"},"hook_circuit_open": "반복 실패로 훅 전달이 중단되었습니다.",- "hook_recent_failures": "최근 훅 호출 {{count}}건이 실패했습니다."+ "hook_recent_failures": "최근 훅 호출 {{count}}건이 실패했습니다.",+ "mcp": {+ "badge": "MCP",+ "description": "이 훅은 플러그인 작성자의 MCP 서버가 제공하는 도구를 채택합니다. 에이전트가 호출할 수 있는 도구를 승인하세요. 나중에 추가된 도구는 승인하기 전까지 채택되지 않습니다.",+ "loading": "도구를 불러오는 중",+ "unreachable": "플러그인의 MCP 서버에 연결할 수 없습니다.",+ "empty": "이 MCP 서버는 현재 제공하는 도구가 없습니다.",+ "drifted": "스키마가 변경됨",+ "save": "승인 저장",+ "approved": "승인된 도구를 업데이트했습니다."+ }},"properties": {"title": "속성",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex caccb45196..3792fd8165 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -392,7 +392,17 @@"unknown": "无法识别的权限 — 请勿安装"},"hook_circuit_open": "连续失败后已停止投递该 hook。",- "hook_recent_failures": "最近有 {{count}} 次 hook 调用失败。"+ "hook_recent_failures": "最近有 {{count}} 次 hook 调用失败。",+ "mcp": {+ "badge": "MCP",+ "description": "该 hook 采用插件作者自己的 MCP server 提供的工具。勾选允许 agent 调用的工具——之后新出现的工具不会自动生效,需要你再次批准。",+ "loading": "正在加载工具",+ "unreachable": "无法连接插件的 MCP server。",+ "empty": "该 MCP server 当前没有提供任何工具。",+ "drifted": "schema 已变更",+ "save": "保存批准",+ "approved": "已更新批准的工具。"+ }},"properties": {"title": "属性",diff --git a/packages/views/plugins/index.ts b/packages/views/plugins/index.tsindex 21aa54395b..caec317119 100644--- a/packages/views/plugins/index.ts+++ b/packages/views/plugins/index.ts@@ -18,3 +18,4 @@ export {} from "./plugin-modal-surface";export type { PluginModalTarget } from "./plugin-modal-surface";export { PluginHookActivity, summarizeInvocations } from "./plugin-hook-activity";+export { PluginMCPApproval, mcpHooks, initialSelection } from "./plugin-mcp-approval";diff --git a/packages/views/plugins/plugin-mcp-approval.test.ts b/packages/views/plugins/plugin-mcp-approval.test.tsnew file mode 100644index 0000000000..41324c0d09--- /dev/null+++ b/packages/views/plugins/plugin-mcp-approval.test.ts@@ -0,0 +1,52 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import type { PluginHook, PluginMCPTool } from "@multica/core/types";+import { initialSelection, mcpHooks } from "./plugin-mcp-approval";++function hook(overrides: Partial<PluginHook>): PluginHook {+ return {+ key: "toolbox",+ name: "Toolbox",+ description: "",+ triggers: ["agent"],+ transport: "mcp",+ ...overrides,+ };+}++function tool(overrides: Partial<PluginMCPTool>): PluginMCPTool {+ return { name: "search", description: "", schema_digest: "", approved: false, drifted: false, ...overrides };+}++describe("mcpHooks", () => {+ it("selects only mcp hooks an agent can reach", () => {+ const hooks = [+ hook({ key: "mcp-agent" }),+ hook({ key: "http-agent", transport: "http" }),+ // Approval says WHICH tools; the trigger says whether an agent may reach+ // them at all. A manual-only mcp hook has no agent to approve tools for.+ hook({ key: "mcp-manual", triggers: ["manual"] }),+ ];+ expect(mcpHooks(hooks).map((entry) => entry.key)).toEqual(["mcp-agent"]);+ });++ it("survives a hook whose triggers are missing entirely", () => {+ const malformed = { key: "k", name: "n", description: "", transport: "mcp" } as PluginHook;+ expect(mcpHooks([malformed])).toEqual([]);+ });+});++describe("initialSelection", () => {+ it("checks the approved tools", () => {+ const tools = [tool({ name: "search", approved: true }), tool({ name: "write" })];+ expect(initialSelection(tools)).toEqual(["search"]);+ });++ // The whole reason drift is surfaced instead of silently re-approved: the+ // administrator approved a specific argument shape, and a changed one is a new+ // decision. Leaving the box checked would turn one Save into blind approval.+ it("unchecks an approved tool whose schema drifted", () => {+ const tools = [tool({ name: "search", approved: true, drifted: true })];+ expect(initialSelection(tools)).toEqual([]);+ });+});diff --git a/packages/views/plugins/plugin-mcp-approval.tsx b/packages/views/plugins/plugin-mcp-approval.tsxnew file mode 100644index 0000000000..57a2334694--- /dev/null+++ b/packages/views/plugins/plugin-mcp-approval.tsx@@ -0,0 +1,145 @@+"use client";++import { useMemo, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { AlertCircle, Loader2 } from "lucide-react";+import { pluginMCPToolsOptions, useApprovePluginMCPTools } from "@multica/core/plugins";+import type { PluginHook, PluginMCPTool } from "@multica/core/types";+import { Alert, AlertDescription, AlertTitle } from "@multica/ui/components/ui/alert";+import { Badge } from "@multica/ui/components/ui/badge";+import { Button } from "@multica/ui/components/ui/button";+import { Checkbox } from "@multica/ui/components/ui/checkbox";+import { Skeleton } from "@multica/ui/components/ui/skeleton";+import { toast } from "sonner";+import { useT } from "../i18n";++/**+ * Approving the tools of an `mcp`-transport hook.+ *+ * An `http` hook needs nothing like this: it declares one endpoint in a manifest+ * the administrator read on the consent screen, and that endpoint is the whole+ * surface. An MCP server decides its own tool list at runtime and may change it+ * whenever it likes, so installing the plugin cannot be the grant — otherwise+ * approving it today authorises whatever the server offers next week.+ *+ * So: discovery is read-only and adopts nothing, and this panel is where an+ * administrator pins a specific set. The server stores each tool with its schema+ * digest, and the daemon refuses to start a connection whose approved tool went+ * missing or whose schema drifted.+ */++/** Which hooks need an approval panel at all. */+export function mcpHooks(hooks: readonly PluginHook[]): PluginHook[] {+ return hooks.filter((hook) => hook.transport === "mcp" && (hook.triggers ?? []).includes("agent"));+}++/**+ * What the save button will send.+ *+ * The complete approved set, never a delta — unchecking a tool and saving is+ * what revokes it, so the checkbox state IS the request. Also why a drifted tool+ * starts unchecked: its schema is not the one that was approved, and leaving it+ * checked would let one click re-approve a shape nobody looked at.+ */+export function initialSelection(tools: readonly PluginMCPTool[]): string[] {+ return tools.filter((tool) => tool.approved && !tool.drifted).map((tool) => tool.name);+}++export function PluginMCPApproval({+ wsId,+ installationId,+ hook,+ canManage,+}: {+ wsId: string;+ installationId: string;+ hook: PluginHook;+ canManage: boolean;+}) {+ const { t } = useT("settings");+ const { data, isLoading, isError, error } = useQuery(pluginMCPToolsOptions(wsId, installationId, hook.key));+ const approve = useApprovePluginMCPTools(wsId, installationId, hook.key);++ const tools = useMemo(() => data ?? [], [data]);+ // null means "not edited yet", so the checkboxes track the server until the+ // administrator touches one. A background refetch then cannot silently undo an+ // edit in progress; saving clears it back to null and the server wins again.+ const [selected, setSelected] = useState<string[] | null>(null);+ const current = selected ?? initialSelection(tools);++ const toggle = (name: string, checked: boolean) => {+ setSelected(checked ? [...current, name] : current.filter((entry) => entry !== name));+ };++ const save = () => {+ approve+ .mutateAsync(current)+ .then(() => {+ setSelected(null);+ toast.success(t(($) => $.plugins.mcp.approved));+ })+ .catch((cause: unknown) => {+ toast.error(cause instanceof Error ? cause.message : t(($) => $.plugins.action_failed));+ });+ };++ return (+ <div className="space-y-2 rounded-md border border-surface-border px-3 py-3">+ <div className="flex items-center gap-2">+ <span className="text-caption font-medium">{hook.name}</span>+ <Badge variant="outline">{t(($) => $.plugins.mcp.badge)}</Badge>+ </div>+ <p className="text-caption text-muted-foreground">{t(($) => $.plugins.mcp.description)}</p>++ {isLoading ? (+ <Skeleton className="h-16 w-full" aria-label={t(($) => $.plugins.mcp.loading)} />+ ) : isError ? (+ <Alert variant="destructive">+ <AlertCircle />+ <AlertTitle>{t(($) => $.plugins.mcp.unreachable)}</AlertTitle>+ {/* The endpoint failing is the actionable part: it is the author's own+ server, and the administrator can only fix it by telling them. */}+ <AlertDescription>{error instanceof Error ? error.message : ""}</AlertDescription>+ </Alert>+ ) : tools.length === 0 ? (+ <p className="text-caption text-muted-foreground">{t(($) => $.plugins.mcp.empty)}</p>+ ) : (+ <>+ <ul className="space-y-1.5">+ {tools.map((tool) => (+ <li key={tool.name} className="flex items-start gap-2">+ <Checkbox+ id={`${installationId}-${hook.key}-${tool.name}`}+ className="mt-0.5"+ disabled={!canManage || approve.isPending}+ checked={current.includes(tool.name)}+ onCheckedChange={(checked) => toggle(tool.name, checked === true)}+ />+ <label+ htmlFor={`${installationId}-${hook.key}-${tool.name}`}+ className="min-w-0 text-caption"+ >+ <span className="font-mono">{tool.name}</span>+ {tool.drifted ? (+ <Badge variant="destructive" className="ml-2">+ {t(($) => $.plugins.mcp.drifted)}+ </Badge>+ ) : null}+ {tool.description ? (+ <span className="block text-muted-foreground">{tool.description}</span>+ ) : null}+ </label>+ </li>+ ))}+ </ul>+ <div className="flex justify-end">+ <Button size="sm" disabled={!canManage || approve.isPending} onClick={save}>+ {approve.isPending ? <Loader2 className="animate-spin" /> : null}+ {t(($) => $.plugins.mcp.save)}+ </Button>+ </div>+ </>+ )}+ </div>+ );+}diff --git a/packages/views/settings/components/plugins-tab.tsx b/packages/views/settings/components/plugins-tab.tsxindex 13a2bc2a5c..263fd54449 100644--- a/packages/views/settings/components/plugins-tab.tsx+++ b/packages/views/settings/components/plugins-tab.tsx@@ -29,7 +29,7 @@ import {import { Skeleton } from "@multica/ui/components/ui/skeleton";import { Textarea } from "@multica/ui/components/ui/textarea";import { Switch } from "@multica/ui/components/ui/switch";-import { PluginHookActivity } from "../../plugins";+import { mcpHooks, PluginHookActivity, PluginMCPApproval } from "../../plugins";import { useT } from "../../i18n";import { SettingsCard, SettingsSection, SettingsTab } from "./settings-layout";@@ -357,6 +357,10 @@ function InstalledPlugin({// failing calls to report.const hasHooks = (installation.hooks ?? []).length > 0;+ // An mcp hook is inert until its tools are approved, so the panel appears for+ // every one of them rather than only when something is already pinned.+ const mcpContributions = mcpHooks(installation.hooks ?? []);+const contributions = [...installation.surfaces.map((surface) => `${surface.name} (${surface.type})`),...installation.hooks.map((hook) => `${hook.name} (${hook.triggers.join(", ")})`),@@ -412,6 +416,21 @@ function InstalledPlugin({<ScopeList scopes={installation.granted_scopes} /></div>+ {mcpContributions.length > 0 ? (+ <div className="space-y-2">+ <div className="text-caption font-medium">{t(($) => $.plugins.mcp.badge)}</div>+ {mcpContributions.map((hook) => (+ <PluginMCPApproval+ key={hook.key}+ wsId={wsId}+ installationId={installation.id}+ hook={hook}+ canManage={canManage}+ />+ ))}+ </div>+ ) : null}+{contributions.length > 0 ? (<div className="space-y-1"><div className="text-caption font-medium">{t(($) => $.plugins.contributes)}</div>diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 043a4a087f..ba3a6f989c 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1303,6 +1303,14 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/workspaces/{workspaceId}/repos", h.GetDaemonWorkspaceRepos)r.Get("/workspaces/{workspaceId}/runtime-profiles", h.DaemonListRuntimeProfiles)+ // Agent-triggered plugin hooks. The daemon's local MCP server calls+ // this when an agent picks one of its tools; the server makes the+ // signed request so the daemon never holds the signing secret.+ r.Post("/tasks/{id}/plugin-hooks", h.InvokeAgentPluginHook)+ // The broker asks for an mcp hook's credential at connection time, so+ // a secret never sits in a task record.+ r.Get("/tasks/{id}/plugin-mcp/{contributionId}/credential", h.ResolvePluginMCPCredential)+r.Post("/runtimes/{runtimeId}/tasks/claim", h.ClaimTaskByRuntime)// Canonical machine-level batch claim (MUL-4257). `/claim` is a// transitional alias; the daemon coordinator targets the canonical@@ -1491,6 +1499,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/plugins/{installationId}/invocations", h.ListPluginInvocations)r.Post("/plugins/{installationId}/token", h.RotatePluginToken)r.Delete("/plugins/{installationId}/token", h.RevokePluginToken)+ // mcp-transport approval. Discovery adopts nothing; the PUT+ // is the grant, and it pins the tools by schema digest.+ r.Get("/plugins/{installationId}/mcp/{hookKey}/tools", h.ListPluginMCPTools)+ r.Put("/plugins/{installationId}/mcp/{hookKey}/tools", h.ApprovePluginMCPTools)r.Put("/plugins/{installationId}/config", h.ConfigurePlugin)r.Post("/plugins/{installationId}/enable", h.EnablePlugin)r.Post("/plugins/{installationId}/disable", h.DisablePlugin)diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 83b894cb3d..ba835f840c 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -16,6 +16,7 @@ import ("github.com/multica-ai/multica/server/pkg/agent""github.com/multica-ai/multica/server/pkg/protocol"+ "github.com/multica-ai/multica/server/pkg/remotemcp")// requestError is returned by postJSON/getJSON when the server responds with an error status.@@ -222,7 +223,15 @@ func (c *Client) ResolveRemoteMCPCredential(ctx context.Context, daemonToken, taCredentialHeader string `json:"credential_header"`Credential string `json:"credential"`}- path := fmt.Sprintf("/api/daemon/tasks/%s/remote-mcp/%s/credential", url.PathEscape(taskID), url.PathEscape(contributionID))+ // A Plugin-contributed connection keeps its credential in the Plugin's own+ // secret storage, which a different route serves. The marker travels on the+ // contribution id because that is all the broker hands back at dial time.+ route := "remote-mcp"+ if strings.HasPrefix(contributionID, remotemcp.PluginContributionPrefix) {+ route = "plugin-mcp"+ }+ path := fmt.Sprintf("/api/daemon/tasks/%s/%s/%s/credential",+ url.PathEscape(taskID), route, url.PathEscape(contributionID))if err := c.getJSONWithToken(ctx, path, daemonToken, &response); err != nil {return nil, err}@@ -1107,3 +1116,69 @@ func (c *Client) getJSONWithToken(ctx context.Context, path, token string, respB}return json.NewDecoder(resp.Body).Decode(respBody)}++// postJSONWithToken is getJSONWithToken's write counterpart, for the daemon's+// task-scoped calls that carry a body.+func (c *Client) postJSONWithToken(ctx context.Context, path, token string, reqBody, respBody any) error {+ encoded, err := json.Marshal(reqBody)+ if err != nil {+ return err+ }+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, bytes.NewReader(encoded))+ if err != nil {+ return err+ }+ req.Header.Set("Content-Type", "application/json")+ if token != "" {+ req.Header.Set("Authorization", "Bearer "+token)+ }+ c.setIdentityHeaders(req)++ resp, err := c.client.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))+ return &requestError{Method: http.MethodPost, Path: path, StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(data))}+ }+ if respBody == nil {+ io.Copy(io.Discard, resp.Body)+ return nil+ }+ return json.NewDecoder(resp.Body).Decode(respBody)+}++// InvokeAgentPluginHook asks the server to make one agent-triggered hook call.+//+// The daemon deliberately does not call the plugin itself: the signing secret+// is derived from the deployment key and stays on the server, and routing+// through it keeps the rate limit, circuit breaker, `net:` destination check+// and invocation record on one code path for every trigger.+func (c *Client) InvokeAgentPluginHook(ctx context.Context, daemonToken, taskID, installationID, hookKey string, input json.RawMessage) (json.RawMessage, error) {+ var response struct {+ Status string `json:"status"`+ Output json.RawMessage `json:"output,omitempty"`+ Error string `json:"error,omitempty"`+ }+ path := fmt.Sprintf("/api/daemon/tasks/%s/plugin-hooks", url.PathEscape(taskID))+ body := map[string]any{"installation_id": installationID, "hook_key": hookKey}+ if len(input) > 0 {+ body["input"] = input+ }+ if err := c.postJSONWithToken(ctx, path, daemonToken, body, &response); err != nil {+ return nil, err+ }+ // A refused or failed hook comes back as a 200 with a status, so that the+ // caller can render it as a TOOL error rather than a broken transport —+ // an unreachable plugin endpoint must not fail the agent's task.+ if response.Status != "ok" {+ if response.Error != "" {+ return nil, errors.New(response.Error)+ }+ return nil, errors.New("the plugin hook did not succeed")+ }+ return response.Output, nil+}diff --git a/server/internal/daemon/client_test.go b/server/internal/daemon/client_test.goindex 48a66173f0..b20846f227 100644--- a/server/internal/daemon/client_test.go+++ b/server/internal/daemon/client_test.go@@ -10,6 +10,8 @@ import ("strings""sync/atomic""testing"++ "github.com/multica-ai/multica/server/pkg/remotemcp""time""github.com/multica-ai/multica/server/pkg/protocol"@@ -113,6 +115,38 @@ func TestClient_ResolveRemoteMCPCredentialUsesExplicitDaemonToken(t *testing.T)}}+// A Plugin's mcp hook shares this resolver and this broker with a workspace's+// own Remote MCP connections, but its credential lives in the Plugin's secret+// storage and a different route serves it. The contribution id is all the+// broker hands back at dial time, so the id carries the marker — and a+// connection without it must keep going to the original route.+func TestClient_ResolveRemoteMCPCredentialRoutesPluginContributions(t *testing.T) {+ var seen []string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ seen = append(seen, r.URL.Path)+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"credential_header":"Authorization","credential":"Bearer upstream"}`))+ }))+ defer srv.Close()++ c := NewClient(srv.URL)+ for _, contribution := range []string{"contribution-1", remotemcp.PluginContributionPrefix + "install-1:toolbox"} {+ if _, err := c.ResolveRemoteMCPCredential(context.Background(), "mdt_task_broker", "task-1", contribution); err != nil {+ t.Fatalf("resolve %q: %v", contribution, err)+ }+ }++ want := []string{+ "/api/daemon/tasks/task-1/remote-mcp/contribution-1/credential",+ "/api/daemon/tasks/task-1/plugin-mcp/plugin:install-1:toolbox/credential",+ }+ for i, path := range want {+ if seen[i] != path {+ t.Fatalf("request %d went to %q, want %q", i, seen[i], path)+ }+ }+}+func TestClient_VersionOmittedWhenUnset(t *testing.T) {srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if got := r.Header.Get("X-Client-Platform"); got != "daemon" {diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 783c574f49..fcec46588d 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -6345,6 +6345,33 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ifor _, diagnostic := range remoteMCPDiagnostics {taskLog.Warn("Remote MCP degraded", "reason", diagnostic)}++ // Agent-trigger plugin hooks, as a second local MCP server beside the+ // broker. A failure to start it degrades to no plugin tools rather than+ // failing the task: an agent that cannot reach a plugin should still work+ // on the issue, which is the same rule that makes a failing tool call a+ // tool error rather than a task error.+ pluginHookConfig, pluginHookServer, pluginHookErr := startTaskPluginHookMCP(+ ctx, task.ID, task.PluginHookTools,+ func(callCtx context.Context, taskID, installationID, hookKey string, input json.RawMessage) (json.RawMessage, error) {+ return d.client.InvokeAgentPluginHook(callCtx, task.RemoteMCPDaemonToken, taskID, installationID, hookKey, input)+ },+ taskLog,+ )+ if pluginHookErr != nil {+ taskLog.Warn("plugin hook tools unavailable", "error", pluginHookErr)+ }+ if pluginHookServer != nil {+ defer pluginHookServer.Close()+ }+ if len(pluginHookConfig) > 0 {+ merged, mergeErr := mergeTaskRemoteMCPConfig(remoteMCPConfig, pluginHookConfig)+ if mergeErr != nil {+ taskLog.Warn("could not merge plugin hook MCP config", "error", mergeErr)+ } else {+ remoteMCPConfig = merged+ }+ }if task.Agent != nil {agentMcpConfig = task.Agent.McpConfigeffectiveMcpConfig = agentMcpConfigdiff --git a/server/internal/daemon/plugin_hook_mcp.go b/server/internal/daemon/plugin_hook_mcp.gonew file mode 100644index 0000000000..2ce519fbaa--- /dev/null+++ b/server/internal/daemon/plugin_hook_mcp.go@@ -0,0 +1,246 @@+package daemon++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "net"+ "net/http"+ "sync"+ "time"+)++// A local MCP server that presents this workspace's plugin hooks as tools.+//+// Unlike the Remote MCP broker beside it, there is no upstream MCP server to+// proxy to: a plugin author writes an HTTP endpoint and never learns what MCP+// is. This synthesises the protocol from the manifest — the hook description+// becomes the tool description, the hook's input_schema becomes the tool's.+//+// A tool call does NOT go to the plugin from here. It goes back to Multica,+// which makes the signed request. The daemon runs on someone's laptop; putting+// the signing secret there would mean every machine running an agent holds a+// credential that can impersonate the server to every plugin backend. Routing+// through the server also means the rate limit, circuit breaker, `net:` check+// and invocation record are the same code for all four triggers.++const (+ pluginHookMCPProtocolVersion = "2024-11-05"+ pluginHookMCPMaxRequestBytes = 1 << 20+ pluginHookMCPCallTimeout = 60 * time.Second+)++// pluginHookInvoker performs one hook call against the Multica server.+type pluginHookInvoker func(ctx context.Context, taskID, installationID, hookKey string, input json.RawMessage) (json.RawMessage, error)++type pluginHookMCPServer struct {+ taskID string+ tools []PluginHookTool+ byName map[string]PluginHookTool+ invoke pluginHookInvoker+ path string+ logger *slog.Logger+}++type pluginHookMCPSet struct {+ server *http.Server+ listener net.Listener+ once sync.Once+}++func (set *pluginHookMCPSet) Close() {+ if set == nil {+ return+ }+ set.once.Do(func() {+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()+ if set.server != nil {+ _ = set.server.Shutdown(ctx)+ }+ if set.listener != nil {+ _ = set.listener.Close()+ }+ })+}++// startTaskPluginHookMCP starts the tool server for one task, if it has tools.+//+// Returns the MCP config fragment to merge into the agent's, exactly like the+// Remote MCP broker, so the two arrive at the agent through one path.+func startTaskPluginHookMCP(lifetimeCtx context.Context, taskID string, tools []PluginHookTool, invoke pluginHookInvoker, logger *slog.Logger) (json.RawMessage, *pluginHookMCPSet, error) {+ if len(tools) == 0 || invoke == nil {+ return nil, nil, nil+ }++ byName := make(map[string]PluginHookTool, len(tools))+ for _, tool := range tools {+ // The server namespaces these, but a duplicate arriving anyway must+ // resolve to exactly one hook rather than whichever came last.+ if _, clash := byName[tool.Name]; clash {+ if logger != nil {+ logger.Warn("plugin hook tool name collided; ignoring the duplicate", "task_id", taskID, "tool", tool.Name)+ }+ continue+ }+ byName[tool.Name] = tool+ }++ listener, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ return nil, nil, fmt.Errorf("listen for plugin hook MCP server: %w", err)+ }+ pathToken, err := randomBrokerToken()+ if err != nil {+ _ = listener.Close()+ return nil, nil, err+ }++ handler := &pluginHookMCPServer{+ taskID: taskID, tools: tools, byName: byName,+ invoke: invoke, path: "/" + pathToken, logger: logger,+ }+ server := &http.Server{Handler: handler, ReadHeaderTimeout: 5 * time.Second}+ set := &pluginHookMCPSet{server: server, listener: listener}++ go func() {+ if serveErr := server.Serve(listener); serveErr != nil && !errors.Is(serveErr, http.ErrServerClosed) && logger != nil {+ logger.Warn("plugin hook MCP server stopped unexpectedly", "task_id", taskID, "error", serveErr)+ }+ }()+ go func() {+ <-lifetimeCtx.Done()+ set.Close()+ }()++ raw, err := json.Marshal(map[string]any{"mcpServers": map[string]any{+ "multica-plugins": map[string]any{+ "type": "http",+ "url": "http://" + listener.Addr().String() + handler.path,+ },+ }})+ if err != nil {+ set.Close()+ return nil, nil, err+ }+ return raw, set, nil+}++type pluginHookMCPRequest struct {+ JSONRPC string `json:"jsonrpc"`+ ID json.RawMessage `json:"id,omitempty"`+ Method string `json:"method"`+ Params json.RawMessage `json:"params,omitempty"`+}++func (s *pluginHookMCPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {+ // The path is a per-task random token, so a process that merely knows the+ // port cannot reach the tools.+ if r.URL.Path != s.path || r.Method != http.MethodPost {+ w.WriteHeader(http.StatusNotFound)+ return+ }+ body, err := io.ReadAll(io.LimitReader(r.Body, pluginHookMCPMaxRequestBytes))+ if err != nil {+ writePluginHookMCPError(w, nil, -32700, "could not read the request")+ return+ }+ var request pluginHookMCPRequest+ if err := json.Unmarshal(body, &request); err != nil {+ writePluginHookMCPError(w, nil, -32700, "request is not valid JSON-RPC")+ return+ }++ switch request.Method {+ case "initialize":+ writePluginHookMCPResult(w, request.ID, map[string]any{+ "protocolVersion": pluginHookMCPProtocolVersion,+ "capabilities": map[string]any{"tools": map[string]any{}},+ "serverInfo": map[string]any{"name": "multica-plugins", "version": "1"},+ })+ case "notifications/initialized":+ // A notification has no id and takes no reply.+ w.WriteHeader(http.StatusAccepted)+ case "tools/list":+ writePluginHookMCPResult(w, request.ID, map[string]any{"tools": s.toolDescriptors()})+ case "tools/call":+ s.handleCall(w, r, request)+ default:+ writePluginHookMCPError(w, request.ID, -32601, "unsupported method "+request.Method)+ }+}++func (s *pluginHookMCPServer) toolDescriptors() []map[string]any {+ descriptors := make([]map[string]any, 0, len(s.tools))+ for _, tool := range s.tools {+ schema := tool.InputSchema+ if len(schema) == 0 {+ // A tool with no declared input still needs a schema, or providers+ // reject the list outright.+ schema = json.RawMessage(`{"type":"object","properties":{}}`)+ }+ descriptors = append(descriptors, map[string]any{+ "name": tool.Name,+ "description": tool.Description,+ "inputSchema": schema,+ })+ }+ return descriptors+}++func (s *pluginHookMCPServer) handleCall(w http.ResponseWriter, r *http.Request, request pluginHookMCPRequest) {+ var params struct {+ Name string `json:"name"`+ Arguments json.RawMessage `json:"arguments,omitempty"`+ }+ if err := json.Unmarshal(request.Params, ¶ms); err != nil {+ writePluginHookMCPError(w, request.ID, -32602, "invalid tool call parameters")+ return+ }+ tool, ok := s.byName[params.Name]+ if !ok {+ writePluginHookMCPError(w, request.ID, -32602, "unknown tool "+params.Name)+ return+ }++ ctx, cancel := context.WithTimeout(r.Context(), pluginHookMCPCallTimeout)+ defer cancel()+ output, err := s.invoke(ctx, s.taskID, tool.InstallationID, tool.HookKey, params.Arguments)+ if err != nil {+ // A TOOL error, not a protocol error. The agent reads this, decides the+ // tool did not work, and carries on with the task — which is the whole+ // point: an unreachable plugin endpoint must not fail somebody's issue.+ if s.logger != nil {+ s.logger.Info("plugin hook tool call failed", "task_id", s.taskID, "tool", tool.Name, "error", err)+ }+ writePluginHookMCPResult(w, request.ID, map[string]any{+ "isError": true,+ "content": []map[string]any{{"type": "text", "text": err.Error()}},+ })+ return+ }++ text := string(output)+ if len(output) == 0 {+ text = "The hook completed and returned nothing."+ }+ writePluginHookMCPResult(w, request.ID, map[string]any{+ "content": []map[string]any{{"type": "text", "text": text}},+ })+}++func writePluginHookMCPResult(w http.ResponseWriter, id json.RawMessage, result any) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": id, "result": result})+}++func writePluginHookMCPError(w http.ResponseWriter, id json.RawMessage, code int, message string) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "jsonrpc": "2.0", "id": id,+ "error": map[string]any{"code": code, "message": message},+ })+}diff --git a/server/internal/daemon/plugin_hook_mcp_test.go b/server/internal/daemon/plugin_hook_mcp_test.gonew file mode 100644index 0000000000..e26dd71b05--- /dev/null+++ b/server/internal/daemon/plugin_hook_mcp_test.go@@ -0,0 +1,133 @@+package daemon++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++// The local MCP server is the daemon's whole contribution to the agent trigger.+// These cover the two things that decide whether it is safe: that a failing+// hook is a TOOL error rather than a broken transport, and that the tool list+// is exactly what the server said it was.++func testHookTools() []PluginHookTool {+ return []PluginHookTool{+ {InstallationID: "inst-1", HookKey: "summarize", Name: "triage_a1b2__summarize",+ Description: "Summarize the thread.", InputSchema: json.RawMessage(`{"type":"object"}`)},+ {InstallationID: "inst-2", HookKey: "summarize", Name: "release_c3d4__summarize",+ Description: "Summarize the release."},+ }+}++func startTestHookMCP(t *testing.T, invoke pluginHookInvoker) (*pluginHookMCPServer, string) {+ t.Helper()+ tools := testHookTools()+ byName := map[string]PluginHookTool{}+ for _, tool := range tools {+ byName[tool.Name] = tool+ }+ return &pluginHookMCPServer{+ taskID: "task-1", tools: tools, byName: byName, invoke: invoke, path: "/token",+ }, "/token"+}++func callMCP(t *testing.T, server *pluginHookMCPServer, path, body string) map[string]any {+ t.Helper()+ request, err := http.NewRequest(http.MethodPost, path, strings.NewReader(body))+ if err != nil {+ t.Fatalf("build request: %v", err)+ }+ recorder := httptest.NewRecorder()+ server.ServeHTTP(recorder, request)+ var decoded map[string]any+ if err := json.Unmarshal(recorder.Body.Bytes(), &decoded); err != nil {+ t.Fatalf("decode response %q: %v", recorder.Body.String(), err)+ }+ return decoded+}++// An unreachable plugin endpoint must not fail the agent's task. It comes back+// as a tool result flagged isError, which the agent reads and works around —+// not as a protocol error, which would look to the agent like its tooling is+// broken.+func TestPluginHookToolFailureIsAToolErrorNotATransportError(t *testing.T) {+ server, path := startTestHookMCP(t, func(context.Context, string, string, string, json.RawMessage) (json.RawMessage, error) {+ return nil, errors.New("hook endpoint did not answer")+ })++ response := callMCP(t, server, path,+ `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"triage_a1b2__summarize","arguments":{}}}`)++ if _, isProtocolError := response["error"]; isProtocolError {+ t.Fatalf("a failing hook produced a JSON-RPC error, which reads as broken tooling: %v", response)+ }+ result, ok := response["result"].(map[string]any)+ if !ok {+ t.Fatalf("no result in %v", response)+ }+ if result["isError"] != true {+ t.Fatalf("the tool result must be flagged as an error, got %v", result)+ }+}++// Both plugins' hooks are offered, under their distinct names.+func TestPluginHookToolsListIsWhatTheServerSent(t *testing.T) {+ server, path := startTestHookMCP(t, nil)+ response := callMCP(t, server, path, `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)++ result, ok := response["result"].(map[string]any)+ if !ok {+ t.Fatalf("no result in %v", response)+ }+ tools, ok := result["tools"].([]any)+ if !ok || len(tools) != 2 {+ t.Fatalf("tools = %v, want the two the server sent", result["tools"])+ }+ names := map[string]bool{}+ for _, entry := range tools {+ tool := entry.(map[string]any)+ names[tool["name"].(string)] = true+ // A tool with no declared input still needs a schema or providers+ // reject the whole list.+ if tool["inputSchema"] == nil {+ t.Fatalf("tool %v has no inputSchema", tool["name"])+ }+ }+ if !names["triage_a1b2__summarize"] || !names["release_c3d4__summarize"] {+ t.Fatalf("both plugins' hooks must appear under distinct names, got %v", names)+ }+}++// A name the server did not send is not callable, however plausible it looks.+func TestPluginHookToolRefusesAnUnknownTool(t *testing.T) {+ called := false+ server, path := startTestHookMCP(t, func(context.Context, string, string, string, json.RawMessage) (json.RawMessage, error) {+ called = true+ return nil, nil+ })+ response := callMCP(t, server, path,+ `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"something__else","arguments":{}}}`)++ if _, isError := response["error"]; !isError {+ t.Fatalf("an unknown tool must be refused, got %v", response)+ }+ if called {+ t.Fatal("an unknown tool reached the invoker")+ }+}++// The path is a per-task random token, so knowing the port is not enough.+func TestPluginHookMCPRefusesTheWrongPath(t *testing.T) {+ server, _ := startTestHookMCP(t, nil)+ request, _ := http.NewRequest(http.MethodPost, "/guessed", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/list"}`))+ recorder := httptest.NewRecorder()+ server.ServeHTTP(recorder, request)+ if recorder.Code != http.StatusNotFound {+ t.Fatalf("status = %d, want 404 for an unknown path", recorder.Code)+ }+}diff --git a/server/internal/daemon/remote_mcp_startup_test.go b/server/internal/daemon/remote_mcp_startup_test.gonew file mode 100644index 0000000000..dfcc02c475--- /dev/null+++ b/server/internal/daemon/remote_mcp_startup_test.go@@ -0,0 +1,166 @@+package daemon++import (+ "context"+ "net/http"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/pkg/remotemcp"+ "github.com/multica-ai/multica/server/pkg/remotemcp/remotemcptest"+)++// Connection startup: the check that makes "the administrator approved these+// tools" mean something at runtime.+//+// The proxy below this layer was already covered against the same fixture, but+// startup itself was not reachable from a test — it validates the endpoint as a+// public HTTPS URL, and the fixture serves plain HTTP on a loopback address. So+// the layer carrying the whole approval guarantee ran zero times. These tests+// exist because MULTICA_PLUGIN_DEV_ORIGINS now lets a caller name that origin.++// The version remotemcptest.Server negotiates. Named once so a fixture change+// is a single edit rather than four.+var fixtureProtocolVersions = []string{"2025-03-26"}++func startupConnection(fixture *remotemcptest.Server, approved []remotemcp.Tool) remotemcp.Connection {+ return remotemcp.Connection{+ InstallationID: "install-1",+ ContributionID: remotemcp.PluginContributionPrefix + "install-1:toolbox",+ ContributionKey: "toolbox",+ Endpoint: fixture.URL,+ Transport: "http",+ EndpointAllowedHosts: []string{"127.0.0.1"},+ ProtocolVersions: fixtureProtocolVersions,+ CredentialHeader: "Authorization",+ ApprovedTools: approved,+ }+}++func fixtureCredential(context.Context, string) (http.Header, error) {+ return http.Header{"Authorization": []string{"Bearer " + remotemcptest.Credential}}, nil+}++// discoveredTools asks the fixture what it offers, so a test can pin the real+// digest instead of hardcoding one that would rot the moment the fixture's+// schema changed.+func discoveredTools(t *testing.T, fixture *remotemcptest.Server) map[string]remotemcp.Tool {+ t.Helper()+ tools, _, err := remotemcp.Discover(context.Background(), fixture.URL,+ []string{"127.0.0.1"}, fixtureProtocolVersions,+ http.Header{"Authorization": []string{"Bearer " + remotemcptest.Credential}})+ if err != nil {+ t.Fatalf("discover fixture tools: %v", err)+ }+ byName := make(map[string]remotemcp.Tool, len(tools))+ for _, tool := range tools {+ byName[tool.Name] = tool+ }+ return byName+}++func startBrokers(t *testing.T, connection remotemcp.Connection) ([]string, error) {+ t.Helper()+ ctx := context.Background()+ config, diagnostics, set, err := startTaskRemoteMCPBrokers(+ ctx, ctx, "task-1", "claude", []remotemcp.Connection{connection}, fixtureCredential, nil)+ if set != nil {+ t.Cleanup(set.Close)+ }+ if err == nil && len(diagnostics) == 0 && len(config) == 0 {+ t.Fatal("startup reported neither a connection, a diagnostic, nor an error")+ }+ return diagnostics, err+}++// The seam is off unless an operator names the origin. Without it this exact+// connection is refused, which is what every production deployment does.+func TestRemoteMCPStartupRefusesALoopbackEndpointByDefault(t *testing.T) {+ fixture := remotemcptest.NewServer()+ defer fixture.Close()++ tools := discoveredToolsWithDevOrigin(t, fixture)+ _, err := startBrokers(t, startupConnection(fixture, []remotemcp.Tool{tools["fixture.read"]}))+ if err == nil {+ t.Fatal("a loopback endpoint started without the operator naming it")+ }+}++// discoveredToolsWithDevOrigin is the same lookup, but scoped so the enclosing+// test can then run WITHOUT the variable set.+func discoveredToolsWithDevOrigin(t *testing.T, fixture *remotemcptest.Server) map[string]remotemcp.Tool {+ t.Helper()+ t.Setenv(remotemcp.DevOriginsEnv, fixture.URL)+ tools := discoveredTools(t, fixture)+ t.Setenv(remotemcp.DevOriginsEnv, "")+ return tools+}++func TestRemoteMCPStartupAcceptsAnApprovedToolSet(t *testing.T) {+ fixture := remotemcptest.NewServer()+ defer fixture.Close()+ t.Setenv(remotemcp.DevOriginsEnv, fixture.URL)++ tools := discoveredTools(t, fixture)+ diagnostics, err := startBrokers(t, startupConnection(fixture, []remotemcp.Tool{tools["fixture.read"]}))+ if err != nil {+ t.Fatalf("an approved, unchanged tool set must start: %v", err)+ }+ if len(diagnostics) != 0 {+ t.Fatalf("unexpected diagnostics: %v", diagnostics)+ }+}++// The server dropped a tool the administrator approved. Refusing here is the+// point: the agent would otherwise get a connection whose contents no longer+// match what anyone signed off on.+func TestRemoteMCPStartupRefusesWhenAnApprovedToolIsMissing(t *testing.T) {+ fixture := remotemcptest.NewServer()+ defer fixture.Close()+ t.Setenv(remotemcp.DevOriginsEnv, fixture.URL)++ approved := []remotemcp.Tool{{Name: "fixture.deleted", SchemaDigest: "sha256:whatever"}}+ _, err := startBrokers(t, startupConnection(fixture, approved))+ if err == nil {+ t.Fatal("startup accepted a connection whose approved tool is gone")+ }+ if !strings.Contains(err.Error(), "missing") {+ t.Fatalf("error should say the approved tool is missing, got: %v", err)+ }+}++// The tool kept its name and changed its arguments. This is the case a+// name-only approval could not catch, and the reason approvals pin a digest.+func TestRemoteMCPStartupRefusesWhenAnApprovedSchemaDrifted(t *testing.T) {+ fixture := remotemcptest.NewServer()+ defer fixture.Close()+ t.Setenv(remotemcp.DevOriginsEnv, fixture.URL)++ approved := []remotemcp.Tool{{Name: "fixture.read", SchemaDigest: "sha256:the-shape-that-was-approved"}}+ _, err := startBrokers(t, startupConnection(fixture, approved))+ if err == nil {+ t.Fatal("startup accepted a tool whose schema no longer matches the approval")+ }+ if !strings.Contains(err.Error(), "drifted") {+ t.Fatalf("error should say the schema drifted, got: %v", err)+ }+}++// A Plugin's MCP server being down must not fail somebody's task. The optional+// policy is what a plugin-contributed connection always carries.+func TestRemoteMCPStartupDegradesAnOptionalConnectionInsteadOfFailingTheTask(t *testing.T) {+ fixture := remotemcptest.NewServer()+ defer fixture.Close()+ t.Setenv(remotemcp.DevOriginsEnv, fixture.URL)++ connection := startupConnection(fixture, []remotemcp.Tool{{Name: "fixture.deleted"}})+ connection.FailurePolicy = "optional"++ diagnostics, err := startBrokers(t, connection)+ if err != nil {+ t.Fatalf("an optional connection must not fail the task: %v", err)+ }+ if len(diagnostics) != 1 || !strings.Contains(diagnostics[0], "toolbox") {+ t.Fatalf("the failure must still be reported as a diagnostic, got: %v", diagnostics)+ }+}diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex 6fec45c21d..1d9acafc9a 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -80,6 +80,10 @@ type Task struct {// RemoteMCPDaemonToken stays inside the daemon and authenticates the local// broker's credential-resolution calls. It must never enter agent env/config.RemoteMCPDaemonToken string `json:"remote_mcp_daemon_token,omitempty"`+ // PluginHookTools are this workspace's agent-trigger plugin hooks, which+ // the local MCP server presents to the agent as tools. Resolved by the+ // server at claim time; the daemon never reads plugin state itself.+ PluginHookTools []PluginHookTool `json:"plugin_hook_tools,omitempty"`// WorkspaceContext mirrors workspace.context (the per-workspace system// prompt set in Settings → General). Server populates this on every claim// regardless of task kind so the daemon can inject `## Workspace Context`@@ -297,3 +301,16 @@ type TaskResult struct {RetiredSessionID string `json:"-"`Usage []TaskUsageEntry `json:"usage,omitempty"` // per-model token usage}++// PluginHookTool is one agent-trigger plugin hook, as the agent will see it.+//+// Mirrors service.PluginHookTool on the wire. Declared here rather than+// imported so the daemon does not depend on the server's service package —+// same reason Task itself is a daemon-side type.+type PluginHookTool struct {+ InstallationID string `json:"installation_id"`+ HookKey string `json:"hook_key"`+ Name string `json:"name"`+ Description string `json:"description"`+ InputSchema json.RawMessage `json:"input_schema,omitempty"`+}diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex e4c569ca78..5aacee3734 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -315,6 +315,11 @@ type AgentTaskResponse struct {IssueID string `json:"issue_id"`WorkspaceID string `json:"workspace_id"`RemoteMCPConnections []remotemcp.Connection `json:"remote_mcp_connections,omitempty"`+ // PluginHookTools are the workspace's agent-trigger plugin hooks, which the+ // daemon renders as MCP tools for this task. Resolved at claim time so+ // disabling or uninstalling a plugin takes effect on the next task rather+ // than whenever a daemon happens to restart.+ PluginHookTools []service.PluginHookTool `json:"plugin_hook_tools,omitempty"`// RemoteMCPDaemonToken is a short-lived, workspace-and-daemon scoped// credential used only by the local daemon's write-only Remote MCP broker.// It is never injected into the agent process.diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 1c383f19f6..91b41453b4 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1896,6 +1896,25 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu// not — because its absence is what tells an upgraded daemon it is talking// to a server too old to have answered the question (MUL-5811).resp.LeaderRoleResolved = true+ // Agent-trigger plugin hooks, as tools. A failure here degrades to no+ // tools rather than failing the claim: a plugin that cannot be listed must+ // not stop an agent from working on the issue.+ if h.PluginService != nil && h.pluginsV1Enabled(r.Context()) {+ if tools, toolErr := h.PluginService.AgentHookTools(r.Context(), parseUUID(runtimeWorkspaceID)); toolErr != nil {+ slog.Warn("plugins: could not list agent hook tools", "workspace_id", runtimeWorkspaceID, "error", toolErr)+ } else {+ resp.PluginHookTools = tools+ }+ // mcp-transport hooks ride the EXISTING broker: the connection shape is+ // what validatePinnedRemoteMCPTools already reads, so an approved tool+ // that went missing or whose schema drifted refuses at startup without+ // any new enforcement code.+ if connections, connErr := h.PluginService.AgentMCPConnections(r.Context(), parseUUID(runtimeWorkspaceID)); connErr != nil {+ slog.Warn("plugins: could not list agent MCP connections", "workspace_id", runtimeWorkspaceID, "error", connErr)+ } else if len(connections) > 0 {+ resp.RemoteMCPConnections = append(resp.RemoteMCPConnections, connections...)+ }+ }supportsCoalescedComments := requestHasClientCapability(r, protocol.DaemonCapabilityCoalescedCommentsV1)// Empty-but-non-nil so pgx persists '{}' rather than NULL for tasks without// comment input. Comment tasks replace this with the ids actually embeddeddiff --git a/server/internal/handler/plugin_agent_hook.go b/server/internal/handler/plugin_agent_hook.gonew file mode 100644index 0000000000..666e0da5ab--- /dev/null+++ b/server/internal/handler/plugin_agent_hook.go@@ -0,0 +1,74 @@+package handler++import (+ "encoding/json"+ "net/http"++ "github.com/go-chi/chi/v5"+)++// The daemon's end of the agent trigger.+//+// An agent calls a tool; the daemon's local MCP server turns that into this+// request; the server performs the signed hook call. The daemon never holds the+// signing secret and never talks to the plugin's endpoint, which is what keeps+// the rate limit, the circuit breaker, the `net:` destination check and the+// invocation record on one code path instead of two.+//+// Authenticated as the daemon and scoped to a claimed task, exactly like the+// rest of /api/daemon: the workspace comes from the task row, so a daemon+// cannot reach an installation in a workspace it is not running a task for.++type invokeAgentHookRequest struct {+ InstallationID string `json:"installation_id"`+ HookKey string `json:"hook_key"`+ Input json.RawMessage `json:"input,omitempty"`+}++// InvokeAgentPluginHook — POST /api/daemon/tasks/{id}/plugin-hooks+func (h *Handler) InvokeAgentPluginHook(w http.ResponseWriter, r *http.Request) {+ if !h.requirePluginsV1(w, r) {+ return+ }+ task, workspaceID, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }++ var req invokeAgentHookRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if req.InstallationID == "" || req.HookKey == "" {+ writeError(w, http.StatusBadRequest, "installation_id and hook_key are required")+ return+ }++ // The installation must belong to the task's workspace. Without this a+ // daemon holding one valid task could name any installation id in the+ // deployment and have the server call it.+ installation, err := h.PluginService.InstallationForWorkspace(r.Context(), parseUUID(workspaceID), req.InstallationID)+ if err != nil {+ writePluginError(w, err, "failed to load the Plugin")+ return+ }++ result, err := h.PluginService.InvokeAgentHook(+ r.Context(), uuidToString(installation.ID), req.HookKey, task.AgentID, req.Input)+ if err != nil {+ // 200 with an error body, deliberately.+ //+ // The daemon turns this into a tool ERROR, and a tool error is+ // something the agent reads and works around. A transport-level failure+ // would instead look to the daemon like the broker itself is broken,+ // which is how one unreachable plugin endpoint ends up failing the+ // whole task — the outcome acceptance criterion 3 forbids.+ writeJSON(w, http.StatusOK, map[string]any{+ "status": result.Status,+ "error": result.Error,+ })+ return+ }+ writeJSON(w, http.StatusOK, result)+}diff --git a/server/internal/handler/plugin_example_test.go b/server/internal/handler/plugin_example_test.gonew file mode 100644index 0000000000..74396c3f60--- /dev/null+++ b/server/internal/handler/plugin_example_test.go@@ -0,0 +1,480 @@+package handler++import (+ "bytes"+ "context"+ "encoding/json"+ "encoding/pem"+ "fmt"+ "net/http"+ "net/http/httptest"+ "net/url"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/util/secretbox"+ "github.com/multica-ai/multica/server/pkg/plugincontract"+ "github.com/multica-ai/multica/server/pkg/remotemcp"+)++// examples/plugins/deploy-sentinel, driven end to end.+//+// This installs the REAL manifest from the repository, not a fixture written+// next to the assertions. That is the point: a hand-written fixture keeps+// passing after the example rots, and the example is what a plugin author+// copies. If somebody breaks the manifest, this is what says so.+//+// The plugin declares all four triggers and both transports, so one install+// covers the whole PR-4 surface: a skill resource lands in the skill table, its+// http hooks reach an agent as tools and are invoked over a real signed request,+// and its mcp hook is discovered and approved.+//+// The only thing rewritten on the way in is the two endpoint hosts — a test+// server's port is not knowable when the manifest is written. Everything else,+// including every tool description an agent reads, is the file's own text.++func exampleRepoDir(t *testing.T) string {+ t.Helper()+ _, thisFile, _, ok := runtime.Caller(0)+ if !ok {+ t.Fatal("cannot locate this test file")+ }+ // server/internal/handler -> repo root+ dir := filepath.Join(filepath.Dir(thisFile), "..", "..", "..", "examples", "plugins", "deploy-sentinel")+ if _, err := os.Stat(filepath.Join(dir, plugincontract.ManifestFilename)); err != nil {+ t.Fatalf("the example plugin is missing: %v", err)+ }+ return dir+}++type exampleServers struct {+ sentinel *httptest.Server+ metrics *httptest.Server+}++func hostOf(t *testing.T, rawURL string) string {+ t.Helper()+ parsed, err := url.Parse(rawURL)+ if err != nil {+ t.Fatalf("parse %q: %v", rawURL, err)+ }+ return parsed.Hostname()+}++// stageExamplePlugin copies the example into a temp MULTICA_PLUGIN_DIR and+// repoints its two endpoints (and the net: scopes that authorise them) at the+// running test servers.+func stageExamplePlugin(t *testing.T, servers exampleServers) (string, []string) {+ t.Helper()+ source := exampleRepoDir(t)+ root := t.TempDir()+ staged := filepath.Join(root, "deploy-sentinel")++ if err := os.CopyFS(staged, os.DirFS(source)); err != nil {+ t.Fatalf("stage the example: %v", err)+ }++ manifestPath := filepath.Join(staged, plugincontract.ManifestFilename)+ raw, err := os.ReadFile(manifestPath)+ if err != nil {+ t.Fatalf("read the example manifest: %v", err)+ }+ sentinelHost, metricsHost := hostOf(t, servers.sentinel.URL), hostOf(t, servers.metrics.URL)+ rewritten := strings.NewReplacer(+ "https://sentinel.example.com", servers.sentinel.URL,+ "https://metrics.example.com", servers.metrics.URL,+ "net:sentinel.example.com", "net:"+sentinelHost,+ "net:metrics.example.com", "net:"+metricsHost,+ ).Replace(string(raw))+ // A net: scope names a host, not a URL, and both test servers land on the+ // same loopback host with different ports. Two identical scope lines are a+ // manifest error, so collapse them — this is an artefact of the rewrite,+ // not of the example.+ rewritten = dedupeScopes(t, rewritten)+ if err := os.WriteFile(manifestPath, []byte(rewritten), 0o644); err != nil {+ t.Fatalf("write the staged manifest: %v", err)+ }++ // Read the scopes back out of the staged file rather than listing them+ // here: granting a set this test maintains by hand would let the manifest+ // add a scope that nothing ever notices.+ var parsed struct {+ Scopes []string `json:"scopes"`+ }+ if err := json.Unmarshal([]byte(rewritten), &parsed); err != nil {+ t.Fatalf("parse the staged manifest: %v", err)+ }+ return root, parsed.Scopes+}++// dedupeScopes rewrites the manifest's scope array in place, dropping repeats+// while preserving order.+func dedupeScopes(t *testing.T, manifest string) string {+ t.Helper()+ var document map[string]json.RawMessage+ if err := json.Unmarshal([]byte(manifest), &document); err != nil {+ t.Fatalf("parse the staged manifest: %v", err)+ }+ var scopes []string+ if err := json.Unmarshal(document["scopes"], &scopes); err != nil {+ t.Fatalf("parse scopes: %v", err)+ }+ seen := map[string]bool{}+ unique := make([]string, 0, len(scopes))+ for _, scope := range scopes {+ if seen[scope] {+ continue+ }+ seen[scope] = true+ unique = append(unique, scope)+ }+ encoded, err := json.Marshal(unique)+ if err != nil {+ t.Fatalf("encode scopes: %v", err)+ }+ document["scopes"] = encoded+ out, err := json.Marshal(document)+ if err != nil {+ t.Fatalf("encode the staged manifest: %v", err)+ }+ return string(out)+}++func installExamplePlugin(t *testing.T, servers exampleServers) string {+ t.Helper()+ withPluginsV1Flag(t, testHandler, true)+ root, scopes := stageExamplePlugin(t, servers)++ plugins := testHandler.PluginService+ previous := *plugins+ plugins.LocalDir = root+ plugins.Host = plugincontract.HostCapabilities()+ // The two test servers run on loopback with self-signed certs, which the+ // outbound guard refuses by design. DevOrigins is the operator opt-in a+ // plugin author uses for exactly this, and it is scoped to these origins.+ plugins.DevOrigins = []string{servers.sentinel.URL, servers.metrics.URL}+ plugins.HookClient = servers.sentinel.Client()+ // The manifest declares two secret config fields, so storing configuration+ // needs the secretbox the deployment would normally supply.+ box, err := secretbox.New(bytes.Repeat([]byte{9}, 32))+ if err != nil {+ t.Fatalf("secretbox.New: %v", err)+ }+ plugins.Secrets = box+ // Signing is what makes a hook call verifiable by the plugin's own server;+ // without a deployment key the engine refuses to call out at all.+ plugins.DeploymentKey = bytes.Repeat([]byte{3}, 32)+ plugins.Callbacks = service.NewCallbackTokens()+ plugins.CallbackBaseURL = "https://multica.test/api/v1/plugin"+ t.Cleanup(func() { *plugins = previous })++ body, _ := json.Marshal(map[string]any{+ "source_url": service.LocalSourcePrefix + "deploy-sentinel",+ "granted_scopes": scopes,+ })+ recorder := httptest.NewRecorder()+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusCreated {+ t.Fatalf("install deploy-sentinel: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ var installed struct {+ ID string `json:"id"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &installed); err != nil {+ t.Fatalf("decode installation: %v", err)+ }+ t.Cleanup(func() {+ cleanup := httptest.NewRecorder()+ testHandler.UninstallPlugin(cleanup, pluginHandlerRequest(http.MethodDelete, "/plugins", nil,+ map[string]string{"id": testWorkspaceID, "installationId": installed.ID}))+ })+ return installed.ID+}++func configureExamplePlugin(t *testing.T, installationID string) {+ t.Helper()+ body, _ := json.Marshal(map[string]any{"values": map[string]any{+ "service_prefix": "prod-",+ "rollback_window_minutes": 60,+ "require_incident_label": true,+ "environment": "production",+ "sentinel_token": "sentinel-secret",+ }})+ recorder := httptest.NewRecorder()+ testHandler.ConfigurePlugin(recorder, pluginHandlerRequest(http.MethodPut, "/config", body,+ map[string]string{"id": testWorkspaceID, "installationId": installationID}))+ if recorder.Code != http.StatusOK {+ t.Fatalf("configure: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+}++// quietServer is the plugin's own hook endpoint: TLS, because the http+// transport's client is supplied by the test and can trust its certificate.+func quietServer(t *testing.T, handler http.HandlerFunc) *httptest.Server {+ t.Helper()+ server := httptest.NewTLSServer(handler)+ t.Cleanup(server.Close)+ return server+}++// metricsServer is the plugin author's own MCP server: HTTPS, because the+// manifest validator requires it and a dev origin does not relax that.+//+// remotemcp.Discover builds its own HTTP client, so the only way for it to+// trust this certificate is the same one a plugin author uses locally —+// MULTICA_PLUGIN_DEV_CA, pointing at a CA bundle.+func metricsServer(t *testing.T) *httptest.Server {+ t.Helper()+ server := httptest.NewTLSServer(http.HandlerFunc(serveMetricsMCP))+ t.Cleanup(server.Close)++ caPath := filepath.Join(t.TempDir(), "dev-ca.pem")+ pem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw})+ if err := os.WriteFile(caPath, pem, 0o600); err != nil {+ t.Fatalf("write the dev CA: %v", err)+ }+ t.Setenv(remotemcp.DevCAEnv, caPath)+ t.Setenv(remotemcp.DevOriginsEnv, server.URL)+ return server+}++// The example's SKILL.md becomes an ordinary workspace skill. No bundle+// pipeline, no digest, no new table — that was the whole claim.+func TestExamplePluginContributesItsSkill(t *testing.T) {+ servers := exampleServers{+ sentinel: quietServer(t, func(http.ResponseWriter, *http.Request) {}),+ metrics: metricsServer(t),+ }+ installationID := installExamplePlugin(t, servers)++ names := skillNamesForInstallation(t, installationID)+ if len(names) != 1 || names[0] != "incident-response" {+ t.Fatalf("skills for the installation = %v, want [incident-response]", names)+ }++ var body string+ if err := testPool.QueryRow(context.Background(),+ `SELECT content FROM skill WHERE plugin_installation_id = $1`, installationID).Scan(&body); err != nil {+ t.Fatalf("read the skill content: %v", err)+ }+ // Asserting on a sentence the skill actually teaches, not on its length: a+ // truncated or mis-resolved entry would still have bytes in it.+ if !strings.Contains(body, "Blast radius") {+ t.Fatalf("the skill did not come from the example's SKILL.md; got %d bytes", len(body))+ }+}++// What an agent working an incident actually sees.+func TestExamplePluginHooksReachAnAgentAsTools(t *testing.T) {+ servers := exampleServers{+ sentinel: quietServer(t, func(http.ResponseWriter, *http.Request) {}),+ metrics: metricsServer(t),+ }+ installExamplePlugin(t, servers)++ tools, err := testHandler.PluginService.AgentHookTools(context.Background(), parseUUID(testWorkspaceID))+ if err != nil {+ t.Fatalf("agent hook tools: %v", err)+ }+ byHook := make(map[string]service.PluginHookTool, len(tools))+ for _, tool := range tools {+ byHook[tool.HookKey] = tool+ }++ for _, hookKey := range []string{"correlate_deploys", "request_rollback"} {+ if _, ok := byHook[hookKey]; !ok {+ t.Fatalf("hook %q declares the agent trigger but is not offered as a tool", hookKey)+ }+ }+ // page_oncall is event-only. An agent being able to page on-call by+ // choosing to would defeat the point of the trigger being separate.+ if _, offered := byHook["page_oncall"]; offered {+ t.Fatal("page_oncall is event-only and must never appear in an agent's tool list")+ }++ rollback := byHook["request_rollback"]+ // The description is the manifest's verbatim, because that text is how the+ // agent decides which tool to reach for.+ if !strings.Contains(rollback.Description, "does NOT roll anything back") {+ t.Fatalf("the tool description must be the manifest's own text, got: %q", rollback.Description)+ }+ if !strings.HasPrefix(rollback.Name, "deploy_sentinel_") || !strings.HasSuffix(rollback.Name, "__request_rollback") {+ t.Fatalf("tool name %q is not namespaced by plugin", rollback.Name)+ }+ if len(rollback.InputSchema) == 0 || !strings.Contains(string(rollback.InputSchema), "deploy_id") {+ t.Fatalf("the manifest's input schema did not reach the agent: %s", rollback.InputSchema)+ }+}++// The whole round trip: an agent calls the tool, Multica signs the request, the+// plugin's own server sees that signature and answers, and the answer comes+// back. Nothing is mocked except the author's business logic, which is theirs.+func TestExamplePluginAgentHookRoundTripIsSigned(t *testing.T) {+ var seenSignature, seenTimestamp, seenHook, seenTrigger string+ var seenConfig map[string]any++ sentinel := quietServer(t, func(w http.ResponseWriter, r *http.Request) {+ var payload struct {+ HookKey string `json:"hook_key"`+ Trigger string `json:"trigger"`+ Config map[string]any `json:"config"`+ }+ _ = json.NewDecoder(r.Body).Decode(&payload)+ seenSignature = r.Header.Get("X-Multica-Signature")+ seenTimestamp = r.Header.Get("X-Multica-Timestamp")+ seenHook, seenTrigger, seenConfig = payload.HookKey, payload.Trigger, payload.Config++ w.Header().Set("Content-Type", "application/json")+ _, _ = fmt.Fprintf(w, `{"deploy_count":1,"summary":"1 deploy to %vcheckout-api"}`, payload.Config["service_prefix"])+ })+ servers := exampleServers{sentinel: sentinel, metrics: metricsServer(t)}++ installationID := installExamplePlugin(t, servers)+ configureExamplePlugin(t, installationID)++ input := json.RawMessage(`{"service":"checkout-api","window_minutes":120}`)+ result, err := testHandler.PluginService.InvokeAgentHook(+ context.Background(), installationID, "correlate_deploys", parseUUID(testUserID), input)+ if err != nil {+ t.Fatalf("agent hook invocation: %v", err)+ }++ if seenHook != "correlate_deploys" || seenTrigger != "agent" {+ t.Fatalf("the plugin saw hook=%q trigger=%q", seenHook, seenTrigger)+ }+ if seenSignature == "" || seenTimestamp == "" {+ t.Fatal("the request reached the plugin unsigned")+ }+ // The plugin's configuration travels with the call — its business rules+ // depend on it, and it must not have to keep a second copy.+ if seenConfig["service_prefix"] != "prod-" {+ t.Fatalf("config did not reach the hook: %v", seenConfig)+ }+ // Structural, not behavioural: a secret-typed value is written to a+ // different table and never reaches installation.Config, so this cannot+ // fail today. It is here for the day somebody merges those two tables.+ if _, leaked := seenConfig["sentinel_token"]; leaked {+ t.Fatal("a secret config value was sent to the hook endpoint")+ }+ if result.Status != "ok" {+ t.Fatalf("hook result status = %q, want ok", result.Status)+ }+ body, _ := json.Marshal(result.Output)+ if !strings.Contains(string(body), "prod-checkout-api") {+ t.Fatalf("the plugin's answer did not come back to the agent: %s", body)+ }+}++// Discovery lists what the metrics server offers; approval is what makes any of+// it callable. That gap is the difference between this transport and http.+func TestExamplePluginMCPToolsNeedApproval(t *testing.T) {+ servers := exampleServers{+ sentinel: quietServer(t, func(http.ResponseWriter, *http.Request) {}),+ metrics: metricsServer(t),+ }+ installationID := installExamplePlugin(t, servers)++ recorder := httptest.NewRecorder()+ testHandler.ListPluginMCPTools(recorder, pluginHandlerRequest(http.MethodGet, "/mcp/tools", nil, map[string]string{+ "id": testWorkspaceID, "installationId": installationID, "hookKey": "metrics",+ }))+ if recorder.Code != http.StatusOK {+ t.Fatalf("discover: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ var discovered struct {+ Tools []struct {+ Name string `json:"name"`+ Approved bool `json:"approved"`+ } `json:"tools"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &discovered); err != nil {+ t.Fatalf("decode tools: %v", err)+ }+ if len(discovered.Tools) != 3 {+ t.Fatalf("discovered %d tools, want the metrics server's 3", len(discovered.Tools))+ }+ for _, tool := range discovered.Tools {+ if tool.Approved {+ t.Fatalf("tool %q reported as approved before anybody approved it", tool.Name)+ }+ }++ // Nothing approved yet, so an agent gets no connection at all.+ connections, err := testHandler.PluginService.AgentMCPConnections(context.Background(), parseUUID(testWorkspaceID))+ if err != nil {+ t.Fatalf("agent mcp connections: %v", err)+ }+ if len(connections) != 0 {+ t.Fatalf("an unapproved mcp hook produced %d connections", len(connections))+ }++ approve, _ := json.Marshal(map[string]any{"tools": []string{"query_timeseries", "list_alerts"}})+ recorder = httptest.NewRecorder()+ testHandler.ApprovePluginMCPTools(recorder, pluginHandlerRequest(http.MethodPut, "/mcp/tools", approve, map[string]string{+ "id": testWorkspaceID, "installationId": installationID, "hookKey": "metrics",+ }))+ if recorder.Code != http.StatusOK {+ t.Fatalf("approve: status=%d body=%s", recorder.Code, recorder.Body.String())+ }++ connections, err = testHandler.PluginService.AgentMCPConnections(context.Background(), parseUUID(testWorkspaceID))+ if err != nil {+ t.Fatalf("agent mcp connections after approval: %v", err)+ }+ if len(connections) != 1 {+ t.Fatalf("got %d connections after approval, want 1", len(connections))+ }+ pinned := map[string]bool{}+ for _, tool := range connections[0].ApprovedTools {+ pinned[tool.Name] = true+ if tool.SchemaDigest == "" {+ t.Fatalf("approved tool %q was pinned without a schema digest", tool.Name)+ }+ }+ // The third tool was discovered and deliberately not ticked. If it rode+ // along, the approval step would be decorative.+ if len(pinned) != 2 || !pinned["query_timeseries"] || !pinned["list_alerts"] {+ t.Fatalf("pinned tools = %v, want exactly the two that were approved", pinned)+ }+}++// serveMetricsMCP mirrors examples/plugins/deploy-sentinel/server/metrics-mcp.mjs.+// The .mjs file is what a person runs by hand; this is what CI runs, so the two+// must offer the same tools.+func serveMetricsMCP(w http.ResponseWriter, r *http.Request) {+ var request struct {+ ID json.RawMessage `json:"id"`+ Method string `json:"method"`+ }+ _ = json.NewDecoder(r.Body).Decode(&request)+ w.Header().Set("Content-Type", "application/json")++ send := func(result any) {+ _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": request.ID, "result": result})+ }+ switch request.Method {+ case "initialize":+ send(map[string]any{+ "protocolVersion": "2025-03-26",+ "capabilities": map[string]any{"tools": map[string]any{}},+ "serverInfo": map[string]any{"name": "deploy-sentinel-metrics", "version": "1.0.0"},+ })+ case "notifications/initialized":+ w.WriteHeader(http.StatusAccepted)+ case "tools/list":+ send(map[string]any{"tools": []map[string]any{+ {"name": "query_timeseries", "description": "Query a metric over a time window.",+ "inputSchema": map[string]any{"type": "object", "required": []string{"metric", "window_minutes"}}},+ {"name": "list_alerts", "description": "Alerts that fired in a window.",+ "inputSchema": map[string]any{"type": "object"}},+ {"name": "service_dependencies", "description": "Which services this one calls.",+ "inputSchema": map[string]any{"type": "object", "required": []string{"service"}}},+ }})+ default:+ send(map[string]any{})+ }+}diff --git a/server/internal/handler/plugin_mcp.go b/server/internal/handler/plugin_mcp.gonew file mode 100644index 0000000000..928b492332--- /dev/null+++ b/server/internal/handler/plugin_mcp.go@@ -0,0 +1,159 @@+package handler++import (+ "encoding/json"+ "net/http"+ "strings"++ "github.com/go-chi/chi/v5"++ "github.com/multica-ai/multica/server/pkg/remotemcp"+)++// Admin approval for an mcp-transport hook.+//+// Discovery is read-only and adopts nothing. Approval is the grant, and it pins+// the tools by schema digest — because an MCP server, unlike an http endpoint,+// decides its own tool list at runtime and can change it after the+// administrator read the manifest.++type pluginMCPToolResponse struct {+ Name string `json:"name"`+ Description string `json:"description"`+ SchemaDigest string `json:"schema_digest"`+ Approved bool `json:"approved"`+ // Drifted marks a tool that IS approved but whose schema no longer matches.+ // Surfaced rather than silently re-approved: the administrator approved a+ // specific shape, and a changed one is a new decision.+ Drifted bool `json:"drifted,omitempty"`+}++// ListPluginMCPTools — GET /api/workspaces/{id}/plugins/{installationId}/mcp/{hookKey}/tools+func (h *Handler) ListPluginMCPTools(w http.ResponseWriter, r *http.Request) {+ installation, ok := h.pluginInstallationFromURL(w, r)+ if !ok {+ return+ }+ hookKey := chi.URLParam(r, "hookKey")++ discovered, err := h.PluginService.DiscoverMCPHookTools(r.Context(), installation, hookKey)+ if err != nil {+ writePluginError(w, err, "failed to reach the Plugin's MCP server")+ return+ }+ approved := h.PluginService.ApprovedMCPTools(installation, hookKey)++ items := make([]pluginMCPToolResponse, 0, len(discovered))+ for _, tool := range discovered {+ pinned, isApproved := approved[tool.Name]+ items = append(items, pluginMCPToolResponse{+ Name: tool.Name,+ Description: tool.Description,+ SchemaDigest: tool.SchemaDigest,+ Approved: isApproved,+ Drifted: isApproved && pinned.SchemaDigest != tool.SchemaDigest,+ })+ }+ writeJSON(w, http.StatusOK, map[string]any{"tools": items})+}++type approvePluginMCPToolsRequest struct {+ // Tools is the complete approved set, not a delta. An administrator+ // removing one is the same request shape as adding one, so there is no way+ // to think you revoked something and have it stay.+ Tools []string `json:"tools"`+}++// ApprovePluginMCPTools — PUT /api/workspaces/{id}/plugins/{installationId}/mcp/{hookKey}/tools+func (h *Handler) ApprovePluginMCPTools(w http.ResponseWriter, r *http.Request) {+ installation, ok := h.pluginInstallationFromURL(w, r)+ if !ok {+ return+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ parsedUserID, ok := parseUUIDOrBadRequest(w, userID, "user_id")+ if !ok {+ return+ }++ var req approvePluginMCPToolsRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }++ updated, err := h.PluginService.ApproveMCPHookTools(+ r.Context(), installation, chi.URLParam(r, "hookKey"), req.Tools, parsedUserID)+ if err != nil {+ writePluginError(w, err, "failed to approve the MCP tools")+ return+ }+ payload, err := h.pluginInstallationPayload(r.Context(), updated)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load the Plugin")+ return+ }+ writeJSON(w, http.StatusOK, payload)+}++// splitPluginContributionID reads back the+// "plugin:<installation uuid>:<hook key>" id AgentMCPConnections built.+//+// The prefix is required, not tolerated: it is what distinguishes a Plugin+// contribution from a workspace's own Remote MCP connection, and those resolve+// their credentials from entirely different places. Both halves after it must+// be present too — a bare installation id would otherwise resolve to an empty+// hook key, and an empty installation id to whatever the workspace lookup makes+// of "", so a daemon holding one contribution's id could name another by+// trimming the string.+func splitPluginContributionID(contribution string) (string, string, bool) {+ trimmed, hasPrefix := strings.CutPrefix(contribution, remotemcp.PluginContributionPrefix)+ if !hasPrefix {+ return "", "", false+ }+ installationID, hookKey, found := strings.Cut(trimmed, ":")+ if !found || installationID == "" || hookKey == "" {+ return "", "", false+ }+ return installationID, hookKey, true+}++// ResolvePluginMCPCredential — GET /api/daemon/tasks/{id}/plugin-mcp/{contributionId}/credential+//+// The daemon's broker asks for the credential at connection time rather than+// receiving it in the claim payload, so a secret never sits in a task record.+// Authenticated as the daemon and scoped to a claimed task, like every other+// /api/daemon route.+func (h *Handler) ResolvePluginMCPCredential(w http.ResponseWriter, r *http.Request) {+ if !h.requirePluginsV1(w, r) {+ return+ }+ _, workspaceID, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }++ installationID, hookKey, ok := splitPluginContributionID(chi.URLParam(r, "contributionId"))+ if !ok {+ writeError(w, http.StatusBadRequest, "malformed contribution id")+ return+ }+ installation, err := h.PluginService.InstallationForWorkspace(r.Context(), parseUUID(workspaceID), installationID)+ if err != nil {+ writePluginError(w, err, "failed to load the Plugin")+ return+ }++ header, credential, err := h.PluginService.MCPHookCredential(r.Context(), installation, hookKey)+ if err != nil {+ writePluginError(w, err, "failed to resolve the credential")+ return+ }+ writeJSON(w, http.StatusOK, map[string]any{+ "credential_header": header,+ "credential": credential,+ })+}diff --git a/server/internal/handler/plugin_mcp_test.go b/server/internal/handler/plugin_mcp_test.gonew file mode 100644index 0000000000..66e12b593e--- /dev/null+++ b/server/internal/handler/plugin_mcp_test.go@@ -0,0 +1,170 @@+package handler++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+)++// The gates in front of an mcp hook's tool list.+//+// Discovery itself reaches the plugin author's own MCP server, so these cover+// what has to hold BEFORE any outbound call happens — the checks that would+// otherwise be a comment claiming they exist. Every one of them refuses without+// the network being involved at all, which is the point: a wrong answer here is+// a request that should never have left the process.++const mcpToolboxManifest = `{+ "manifest_version": 1,+ "key": "com.example.toolbox",+ "name": "Toolbox",+ "version": "1.0.0",+ "author": { "name": "example" },+ "scopes": ["issues:read", "net:tools.example.com"],+ "contributes": {+ "hooks": [{+ "key": "toolbox",+ "name": "Toolbox",+ "description": "Tools from an external MCP server.",+ "triggers": ["agent"],+ "transport": { "type": "mcp", "url": "https://tools.example.com/mcp" }+ }]+ }+}`++// An http hook declares one endpoint the administrator already saw on the+// consent screen. Asking it for a tool list is a category error, not an empty+// list — answering `{"tools":[]}` would make the UI offer an approval panel for+// a hook that has nothing to approve.+const httpHookManifest = `{+ "manifest_version": 1,+ "key": "com.example.plainhook",+ "name": "Plain Hook",+ "version": "1.0.0",+ "author": { "name": "example" },+ "scopes": ["issues:read", "net:hooks.example.com"],+ "contributes": {+ "hooks": [{+ "key": "notify",+ "name": "Notify",+ "description": "Posts to an endpoint.",+ "triggers": ["manual"],+ "transport": { "type": "http", "url": "https://hooks.example.com/notify" }+ }]+ }+}`++func installMCPPlugin(t *testing.T, manifest string, scopes []string) string {+ t.Helper()+ withPluginsV1Flag(t, testHandler, true)+ source := withLocalPluginSource(t, manifest)+ body, _ := json.Marshal(map[string]any{"source_url": source, "granted_scopes": scopes})+ recorder := httptest.NewRecorder()+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusCreated {+ t.Fatalf("install: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ var installed struct {+ ID string `json:"id"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &installed); err != nil {+ t.Fatalf("decode installation: %v", err)+ }+ t.Cleanup(func() {+ cleanup := httptest.NewRecorder()+ testHandler.UninstallPlugin(cleanup, pluginHandlerRequest(http.MethodDelete, "/plugins",+ nil, map[string]string{"id": testWorkspaceID, "installationId": installed.ID}))+ })+ return installed.ID+}++func listMCPTools(t *testing.T, installationID, hookKey string) *httptest.ResponseRecorder {+ t.Helper()+ recorder := httptest.NewRecorder()+ testHandler.ListPluginMCPTools(recorder, pluginHandlerRequest(http.MethodGet, "/mcp/tools", nil, map[string]string{+ "id": testWorkspaceID, "installationId": installationID, "hookKey": hookKey,+ }))+ return recorder+}++func TestMCPToolListRejectsAnHTTPTransportHook(t *testing.T) {+ installationID := installMCPPlugin(t, httpHookManifest, []string{"issues:read", "net:hooks.example.com"})++ recorder := listMCPTools(t, installationID, "notify")+ if recorder.Code != http.StatusBadRequest {+ t.Fatalf("an http hook must not answer a tool list: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+}++func TestMCPToolListRejectsAnUnknownHook(t *testing.T) {+ installationID := installMCPPlugin(t, mcpToolboxManifest, []string{"issues:read", "net:tools.example.com"})++ recorder := listMCPTools(t, installationID, "does-not-exist")+ if recorder.Code != http.StatusNotFound {+ t.Fatalf("status=%d body=%s, want 404", recorder.Code, recorder.Body.String())+ }+}++// The `net:` scope is the consent, and a hook's own transport URL is not+// self-authorizing. A manifest can declare any endpoint it likes; what makes it+// reachable is the scope line the administrator read and approved, so a manifest+// that declares an mcp hook and no `net:` scope gets refused before any DNS+// lookup happens.+const scopelessMCPManifest = `{+ "manifest_version": 1,+ "key": "com.example.scopeless",+ "name": "Scopeless",+ "version": "1.0.0",+ "author": { "name": "example" },+ "scopes": ["issues:read"],+ "contributes": {+ "hooks": [{+ "key": "toolbox",+ "name": "Toolbox",+ "description": "Points somewhere it was never granted.",+ "triggers": ["agent"],+ "transport": { "type": "mcp", "url": "https://tools.example.com/mcp" }+ }]+ }+}`++// Refused at INSTALL, not at discovery: manifest validation already requires+// every hook transport URL to sit inside a declared `net:` scope, and that check+// does not care which transport it is. The equivalent check inside+// DiscoverMCPHookTools is a second layer behind this one, not the gate.+func TestMCPHookWithoutANetScopeCannotBeInstalled(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ source := withLocalPluginSource(t, scopelessMCPManifest)+ body, _ := json.Marshal(map[string]any{"source_url": source, "granted_scopes": []string{"issues:read"}})++ recorder := httptest.NewRecorder()+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))+ if recorder.Code == http.StatusCreated {+ t.Fatal("a hook pointing outside its granted net: scopes was installed")+ }+}++// The daemon's credential route keys on "<installation>:<hook>". A malformed id+// must be refused rather than resolved as a bare installation id — otherwise a+// daemon holding an id for one contribution could name another by trimming it.+func TestPluginContributionIDNeedsBothHalves(t *testing.T) {+ refused := []string{+ "", "no-colon", ":toolbox", "installation:",+ "plugin:", "plugin:no-colon", "plugin::toolbox", "plugin:installation:",+ // Unprefixed. A workspace's own Remote MCP connection resolves its+ // credential from somewhere else entirely, so its id must not be+ // answerable here even when it happens to have the right shape.+ "1f0d9b7e-0000-0000-0000-000000000000:toolbox",+ }+ for _, contribution := range refused {+ if _, _, ok := splitPluginContributionID(contribution); ok {+ t.Fatalf("contribution %q was accepted; it must be refused", contribution)+ }+ }++ installationID, hookKey, ok := splitPluginContributionID("plugin:1f0d9b7e-0000-0000-0000-000000000000:toolbox")+ if !ok || installationID != "1f0d9b7e-0000-0000-0000-000000000000" || hookKey != "toolbox" {+ t.Fatalf("split = (%q, %q, %v), want the two halves", installationID, hookKey, ok)+ }+}diff --git a/server/internal/handler/plugin_skill_test.go b/server/internal/handler/plugin_skill_test.gonew file mode 100644index 0000000000..22f857e7f7--- /dev/null+++ b/server/internal/handler/plugin_skill_test.go@@ -0,0 +1,205 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"+)++// A plugin's skill resource becomes an ordinary workspace skill, and uninstall+// takes it away again.+//+// The whole design claim is that this needs no new machinery: the skill table+// already holds a SKILL.md, so the only addition is remembering who contributed+// it. These tests are about that ownership — that it installs, that an upgrade+// prunes what the manifest dropped, that uninstall removes exactly the+// plugin's rows, and that a plugin cannot overwrite a skill a person wrote.++const skillPluginManifest = `{+ "manifest_version": 1,+ "key": "com.example.skilled",+ "name": "Skilled",+ "version": "1.0.0",+ "author": { "name": "example" },+ "scopes": ["issues:read"],+ "contributes": {+ "resources": [{ "type": "skill", "key": "pr-review", "entry": "skills/pr-review/SKILL.md" }]+ }+}`++const prReviewSkill = `---+name: pr-review+description: Review a pull request against the repository's conventions.+---++Read the diff, then check it against CLAUDE.md.+`++func writePluginSkillFile(t *testing.T, root, key, content string) {+ t.Helper()+ dir := filepath.Join(root, "hello", "skills", key)+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatalf("create skill dir: %v", err)+ }+ if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(content), 0o644); err != nil {+ t.Fatalf("write SKILL.md: %v", err)+ }+}++func installSkillPlugin(t *testing.T, root, manifest string) string {+ t.Helper()+ source := withLocalPluginSourceIn(t, root, manifest)+ body, _ := json.Marshal(map[string]any{+ "source_url": source,+ "granted_scopes": []string{"issues:read"},+ })+ recorder := httptest.NewRecorder()+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))+ if recorder.Code != http.StatusCreated {+ t.Fatalf("install: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ var installed struct {+ ID string `json:"id"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &installed); err != nil {+ t.Fatalf("decode installation: %v", err)+ }+ return installed.ID+}++func skillNamesForInstallation(t *testing.T, installationID string) []string {+ t.Helper()+ rows, err := testPool.Query(context.Background(),+ `SELECT name FROM skill WHERE plugin_installation_id = $1 ORDER BY name`, installationID)+ if err != nil {+ t.Fatalf("query plugin skills: %v", err)+ }+ defer rows.Close()+ names := []string{}+ for rows.Next() {+ var name string+ if err := rows.Scan(&name); err != nil {+ t.Fatalf("scan: %v", err)+ }+ names = append(names, name)+ }+ return names+}++func TestPluginSkillInstallsAndIsRemovedOnUninstall(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ root := t.TempDir()+ writePluginSkillFile(t, root, "pr-review", prReviewSkill)+ installationID := installSkillPlugin(t, root, skillPluginManifest)++ names := skillNamesForInstallation(t, installationID)+ if len(names) != 1 || names[0] != "pr-review" {+ t.Fatalf("installed skills = %v, want [pr-review]", names)+ }++ // The content is the file, not a stub: a skill that installs empty is worse+ // than one that fails, because the agent gets a plausible no-op.+ var content, description string+ if err := testPool.QueryRow(context.Background(),+ `SELECT content, description FROM skill WHERE plugin_installation_id = $1`, installationID,+ ).Scan(&content, &description); err != nil {+ t.Fatalf("read skill: %v", err)+ }+ if len(content) < 20 {+ t.Fatalf("skill content looks empty: %q", content)+ }+ if description == "" {+ t.Fatal("description should come from the frontmatter")+ }++ uninstall := httptest.NewRecorder()+ testHandler.UninstallPlugin(uninstall, pluginHandlerRequest(http.MethodDelete, "/plugins", nil, map[string]string{+ "id": testWorkspaceID, "installationId": installationID,+ }))+ if uninstall.Code != http.StatusNoContent {+ t.Fatalf("uninstall: status=%d body=%s", uninstall.Code, uninstall.Body.String())+ }+ if remaining := skillNamesForInstallation(t, installationID); len(remaining) != 0 {+ t.Fatalf("uninstall left skills behind: %v", remaining)+ }+}++// An upgrade that drops a skill must remove it. Otherwise a renamed skill+// leaves its predecessor in the workspace forever, with nothing to attribute+// it to.+func TestPluginSkillUpgradePrunesWhatTheManifestDropped(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ root := t.TempDir()+ writePluginSkillFile(t, root, "pr-review", prReviewSkill)+ installationID := installSkillPlugin(t, root, skillPluginManifest)++ // Version 2 renames the skill.+ writePluginSkillFile(t, root, "code-review", prReviewSkill)+ upgraded := `{+ "manifest_version": 1,+ "key": "com.example.skilled",+ "name": "Skilled",+ "version": "2.0.0",+ "author": { "name": "example" },+ "scopes": ["issues:read"],+ "contributes": {+ "resources": [{ "type": "skill", "key": "code-review", "entry": "skills/code-review/SKILL.md" }]+ }+}`+ if got := installSkillPlugin(t, root, upgraded); got != installationID {+ t.Fatalf("upgrade created a second installation: %s != %s", got, installationID)+ }++ names := skillNamesForInstallation(t, installationID)+ if len(names) != 1 || names[0] != "code-review" {+ t.Fatalf("after upgrade skills = %v, want [code-review] — the dropped one was not pruned", names)+ }+}++// A plugin must not be able to take over a name a person already used. The+// upsert is scoped to rows this installation owns, so the collision surfaces+// as a failed install rather than a silently replaced skill.+func TestPluginSkillWillNotOverwriteAHumanAuthoredSkill(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)++ var existingID string+ if err := testPool.QueryRow(context.Background(),+ `INSERT INTO skill (workspace_id, name, description, content) VALUES ($1, 'pr-review', 'mine', 'written by a person') RETURNING id`,+ testWorkspaceID,+ ).Scan(&existingID); err != nil {+ t.Fatalf("seed human skill: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM skill WHERE id = $1`, existingID)+ })++ root := t.TempDir()+ writePluginSkillFile(t, root, "pr-review", prReviewSkill)+ source := withLocalPluginSourceIn(t, root, skillPluginManifest)+ body, _ := json.Marshal(map[string]any{+ "source_url": source,+ "granted_scopes": []string{"issues:read"},+ })+ recorder := httptest.NewRecorder()+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins", body, map[string]string{"id": testWorkspaceID}))+ if recorder.Code == http.StatusCreated {+ t.Fatal("a plugin claiming an existing skill name must not install")+ }++ // And the person's skill is untouched.+ var content string+ if err := testPool.QueryRow(context.Background(),+ `SELECT content FROM skill WHERE id = $1`, existingID).Scan(&content); err != nil {+ t.Fatalf("re-read human skill: %v", err)+ }+ if content != "written by a person" {+ t.Fatalf("the human-authored skill was overwritten: %q", content)+ }+}diff --git a/server/internal/migrations/migrations_lint_test.go b/server/internal/migrations/migrations_lint_test.goindex c4b6f6c54c..a6e95589aa 100644--- a/server/internal/migrations/migrations_lint_test.go+++ b/server/internal/migrations/migrations_lint_test.go@@ -15,6 +15,11 @@ import (const maxLegacyMigrationPrefix = 148var legacyDuplicateMigrationStems = map[string][]string{+ // 362 is not historical: two PRs took the prefix within the same hour and+ // both merged. It is listed here rather than renamed because the runner+ // keys the ledger on the full stem, so renaming a migration that already+ // ran would re-run it in every environment that has it.+ "362": {"362_agent_task_durable_work_dir", "362_plugin_hook_engine"},"020": {"020_issue_number", "020_task_session"},"026": {"026_comment_reactions", "026_task_messages"},"029": {"029_attachment", "029_daemon_token", "029_drop_daemon_pairing"},diff --git a/server/internal/service/plugin.go b/server/internal/service/plugin.goindex a0eda41e30..f718f40afb 100644--- a/server/internal/service/plugin.go+++ b/server/internal/service/plugin.go@@ -445,7 +445,17 @@ func (s *PluginService) InstallPlugin(ctx context.Context, workspaceID, userID pPluginKey: manifest.Key,})if errors.Is(err, pgx.ErrNoRows) {- installation, createErr := s.Queries.CreatePluginInstallation(ctx, db.CreatePluginInstallationParams{+ // A transaction even though it is one row: the skill resources land in+ // the same commit. An installation whose skills half-arrived is worse+ // than one that failed, because the missing half is invisible.+ tx, txErr := s.TxStarter.Begin(ctx)+ if txErr != nil {+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "begin install", Err: txErr}+ }+ defer func() { _ = tx.Rollback(ctx) }()+ queries := s.Queries.WithTx(tx)++ installation, createErr := queries.CreatePluginInstallation(ctx, db.CreatePluginInstallationParams{WorkspaceID: workspaceID,PluginKey: manifest.Key,SourceUrl: sourceURL,@@ -462,6 +472,12 @@ func (s *PluginService) InstallPlugin(ctx context.Context, workspaceID, userID p}return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "install plugin", Err: createErr}}+ if skillErr := s.InstallSkillResources(ctx, queries, installation, manifest, sourceURL, userID); skillErr != nil {+ return db.PluginInstallation{}, skillErr+ }+ if commitErr := tx.Commit(ctx); commitErr != nil {+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "commit install", Err: commitErr}+ }return installation, nil}if err != nil {@@ -502,6 +518,12 @@ func (s *PluginService) InstallPlugin(ctx context.Context, workspaceID, userID pif err != nil {return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "upgrade plugin", Err: err}}+ // Re-run on upgrade so a changed SKILL.md takes effect and a dropped one is+ // pruned. Same transaction as the manifest snapshot: the two must never+ // disagree about what this version contributes.+ if err := s.InstallSkillResources(ctx, queries, updated, manifest, sourceURL, userID); err != nil {+ return db.PluginInstallation{}, err+ }if err := tx.Commit(ctx); err != nil {return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "commit upgrade", Err: err}}@@ -769,6 +791,12 @@ func (s *PluginService) Uninstall(ctx context.Context, installation db.PluginInsif err := queries.DeletePluginInvocationsByInstallation(ctx, installation.ID); err != nil {return &PluginError{Kind: PluginErrorUnavailable, Message: "delete plugin invocations", Err: err}}+ // The skills this installation contributed go with it. Scoped by+ // plugin_installation_id, so a skill a person wrote is untouched even if it+ // happens to share a name with something the plugin once provided.+ if err := queries.DeletePluginSkillsByInstallation(ctx, installation.ID); err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "delete plugin skills", Err: err}+ }if err := queries.DeletePluginInstallation(ctx, installation.ID); err != nil {return &PluginError{Kind: PluginErrorUnavailable, Message: "delete plugin installation", Err: err}}@@ -797,3 +825,31 @@ func (s *PluginService) InstallationForWorkspace(ctx context.Context, workspaceI}return installation, nil}++// readLocalFile reads a file from inside a local plugin directory.+//+// Same containment as readLocalManifest, plus one more: the joined path is+// re-checked against the plugin's own directory after cleaning. `entry` is+// validated at manifest-parse time to be relative and traversal-free, but this+// is the layer that touches the filesystem and it does not get to assume that.+func (s *PluginService) readLocalFile(name, entry string) ([]byte, error) {+ if s.LocalDir == "" {+ return nil, pluginErrf(PluginErrorInvalid, "local plugin sources require MULTICA_PLUGIN_DIR")+ }+ if name == "" || strings.ContainsAny(name, `/\`) || strings.HasPrefix(name, ".") {+ return nil, pluginErrf(PluginErrorInvalid, "local plugin source must be a single directory name under MULTICA_PLUGIN_DIR")+ }+ root := filepath.Join(s.LocalDir, name)+ path := filepath.Clean(filepath.Join(root, entry))+ if path != root && !strings.HasPrefix(path, root+string(os.PathSeparator)) {+ return nil, pluginErrf(PluginErrorInvalid, "plugin resource %q escapes its directory", entry)+ }+ raw, err := os.ReadFile(path)+ if errors.Is(err, os.ErrNotExist) {+ return nil, pluginErrf(PluginErrorNotFound, "plugin resource %q was not found", entry)+ }+ if err != nil {+ return nil, &PluginError{Kind: PluginErrorInvalid, Message: "read plugin resource", Err: err}+ }+ return raw, nil+}diff --git a/server/internal/service/plugin_agent_tools.go b/server/internal/service/plugin_agent_tools.gonew file mode 100644index 0000000000..02647e2ad5--- /dev/null+++ b/server/internal/service/plugin_agent_tools.go@@ -0,0 +1,152 @@+package service++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "regexp"+ "sort"+ "strings"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/pkg/plugincontract"+)++// The `agent` trigger: a plugin hook offered to an agent as an MCP tool.+//+// This is the fourth call site, and the one that is NOT the host deciding to+// call something. An agent sees a tool, reads its description, and chooses. That+// choice is the whole reason hooks may be reached from an agent at all: the+// alternative — a hook that must run before or after every turn — is a third+// party holding the product's main loop open, which is why no such position+// exists anywhere in this design.+//+// The daemon renders these as tools but does NOT call the plugin. A tool call+// goes back to the server, which performs the signed request. The signing secret+// is derived from the deployment key and never leaves this process; equally+// important, routing through the server means the rate limit, the circuit+// breaker, the `net:` destination check and the invocation record all apply+// exactly as they do for every other trigger, rather than being reimplemented+// daemon-side where they would drift.++// PluginHookTool is one hook, described the way an agent will see it.+type PluginHookTool struct {+ InstallationID string `json:"installation_id"`+ HookKey string `json:"hook_key"`+ // Name is what the agent sees, namespaced so two plugins contributing the+ // same hook key do not collide.+ Name string `json:"name"`+ // Description is the manifest's hook description verbatim: it is what the+ // agent reads to decide whether to call this, so the plugin author writes+ // it and the host does not paraphrase.+ Description string `json:"description"`+ InputSchema json.RawMessage `json:"input_schema,omitempty"`+}++// toolNameUnsafe matches everything MCP tool names should not contain. Agents+// and providers vary in what they accept; letters, digits and underscores are+// the intersection that works everywhere.+var toolNameUnsafe = regexp.MustCompile(`[^a-zA-Z0-9_]+`)++// PluginToolName namespaces a hook so two plugins can both contribute a hook+// called "summarize" without one shadowing the other.+//+// The naive version of this — sanitize both halves and join with an underscore+// — is not injective, and a test caught it: a plugin key uses `.` and `-`, both+// of which have to become `_`, so `a.b` and `a-b` collapse together, and+// `a.b_` + `c` collides with `a.b` + `c`. Two different plugins would then be+// offering the agent one tool name, and whichever was registered last would+// answer for both.+//+// So the prefix carries a short digest of the FULL plugin key rather than a+// lossy transliteration of it. The readable part is the last segment, which is+// what a person recognises; the digest is what makes it unique.+//+// The `__` separator is safe because a hook key cannot contain one: its pattern+// requires an alphanumeric after every underscore, so a doubled underscore is+// unrepresentable.+func PluginToolName(pluginKey, hookKey string) string {+ clean := func(value string) string {+ return strings.Trim(toolNameUnsafe.ReplaceAllString(value, "_"), "_")+ }+ segments := strings.Split(pluginKey, ".")+ readable := clean(segments[len(segments)-1])+ if readable == "" {+ readable = "plugin"+ }+ digest := sha256.Sum256([]byte(pluginKey))+ return readable + "_" + hex.EncodeToString(digest[:])[:6] + "__" + clean(hookKey)+}++// AgentHookTools lists the hooks an agent running in this workspace may call.+//+// Disabled installations are skipped, which is what makes disabling a plugin+// take effect on the next task rather than only in the UI. An uninstalled one+// has no row at all.+func (s *PluginService) AgentHookTools(ctx context.Context, workspaceID pgtype.UUID) ([]PluginHookTool, error) {+ installations, err := s.Queries.ListWorkspacePluginInstallations(ctx, workspaceID)+ if err != nil {+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "list plugin installations", Err: err}+ }++ tools := make([]PluginHookTool, 0)+ for _, installation := range installations {+ if !installation.Enabled {+ continue+ }+ manifest, err := ParseInstallationManifest(installation)+ if err != nil {+ // One unreadable manifest must not hide every other plugin's tools.+ continue+ }+ for _, hook := range manifest.Contributes.Hooks {+ if !HookAllowsTrigger(hook, plugincontract.TriggerAgent) {+ continue+ }+ tools = append(tools, PluginHookTool{+ InstallationID: uuidString(installation.ID),+ HookKey: hook.Key,+ Name: PluginToolName(manifest.Key, hook.Key),+ Description: hook.Description,+ InputSchema: hook.InputSchema,+ })+ }+ }+ // Stable order so a task's tool list does not reshuffle between claims for+ // no reason, which shows up as cache churn in provider-side prompt caching.+ sort.Slice(tools, func(i, j int) bool { return tools[i].Name < tools[j].Name })+ return tools, nil+}++// InvokeAgentHook runs one agent-triggered hook.+//+// The actor is the AGENT, not the person who filed the issue and not the+// plugin: an agent chose to call this, so the writes it produces are the+// agent's, exactly as they would be if the agent had written them directly.+// author_type already has a value for that, which is why this trigger needs no+// new one.+func (s *PluginService) InvokeAgentHook(ctx context.Context, installationID, hookKey string, agentID pgtype.UUID, input json.RawMessage) (HookResult, error) {+ caller, err := s.AuthorizePluginAction(ctx, installationID, pgtype.UUID{}, "")+ if err != nil {+ return HookResult{}, err+ }+ hook, err := FindHook(caller.Installation, hookKey)+ if err != nil {+ return HookResult{}, err+ }+ return s.InvokeHook(ctx, HookInvocation{+ Installation: caller.Installation,+ Hook: hook,+ Trigger: plugincontract.TriggerAgent,+ Actor: HookActor{Type: "agent", ID: agentID},+ Input: rawInputOrNil(input),+ }, 1)+}++func rawInputOrNil(raw json.RawMessage) any {+ if len(raw) == 0 {+ return nil+ }+ return raw+}diff --git a/server/internal/service/plugin_agent_tools_test.go b/server/internal/service/plugin_agent_tools_test.gonew file mode 100644index 0000000000..68a6937cec--- /dev/null+++ b/server/internal/service/plugin_agent_tools_test.go@@ -0,0 +1,109 @@+package service++import (+ "encoding/json"+ "testing"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Two plugins may both contribute a hook called "summarize". The agent sees one+// tool list, so the names have to be distinguishable in it.+func TestPluginToolNameNamespacesByPlugin(t *testing.T) {+ first := PluginToolName("com.example.triage", "summarize")+ second := PluginToolName("ai.multica.release", "summarize")+ if first == second {+ t.Fatalf("two plugins' hooks collapsed to one tool name: %q", first)+ }+ for _, name := range []string{first, second} {+ for _, r := range name {+ isSafe := (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_'+ if !isSafe {+ t.Fatalf("tool name %q contains %q, which providers vary on accepting", name, r)+ }+ }+ }+}++// The separator has to be one that cannot appear inside either half, or two+// different (plugin, hook) pairs can still land on the same string.+func TestPluginToolNameSeparatorCannotBeForged(t *testing.T) {+ // `a.b` + `c` vs `a.b_` + `c`: with a single-underscore separator both+ // become a_b_c.+ if PluginToolName("a.b", "c") == PluginToolName("a.b_", "c") {+ t.Fatal("a plugin key ending in a separator character collided with another")+ }+ if PluginToolName("x", "y__z") == PluginToolName("x__y", "z") {+ t.Fatal("a hook key containing the separator collided with a different pair")+ }+}++// A hook that did not declare the agent trigger is not a tool. The host does+// not get to offer a call site the manifest never listed.+func TestAgentHookToolsOnlyIncludesDeclaredAgentHooks(t *testing.T) {+ installation := db.PluginInstallation{+ ID: testInstallationID(t),+ Enabled: true,+ Manifest: []byte(`{+ "manifest_version": 1,+ "key": "com.example.mixed",+ "name": "Mixed",+ "description": "d",+ "version": "1.0.0",+ "author": {"name": "example"},+ "scopes": ["net:example.com"],+ "contributes": {"hooks": [+ {"key": "for_agent", "name": "For agent", "description": "Agent may call this.",+ "triggers": ["agent"], "transport": {"type": "http", "url": "https://example.com/a"}},+ {"key": "manual_only", "name": "Manual only", "description": "A person picks this.",+ "triggers": ["manual"], "transport": {"type": "http", "url": "https://example.com/m"}}+ ]}+ }`),+ }++ manifest, err := ParseInstallationManifest(installation)+ if err != nil {+ t.Fatalf("parse manifest: %v", err)+ }+ agentHooks := 0+ for _, hook := range manifest.Contributes.Hooks {+ if HookAllowsTrigger(hook, "agent") {+ agentHooks+++ if hook.Key != "for_agent" {+ t.Fatalf("hook %q is not an agent hook but was treated as one", hook.Key)+ }+ }+ }+ if agentHooks != 1 {+ t.Fatalf("agent hooks = %d, want 1", agentHooks)+ }+}++// The description the agent reads is the plugin author's, verbatim. It is what+// the agent decides on, so the host must not paraphrase it.+func TestAgentToolDescriptionIsTheManifestText(t *testing.T) {+ const wanted = "Summarize the discussion so far into decisions and open questions."+ installation := db.PluginInstallation{+ ID: testInstallationID(t),+ Enabled: true,+ Manifest: json.RawMessage(`{+ "manifest_version": 1,+ "key": "com.example.sum",+ "name": "Sum",+ "description": "d",+ "version": "1.0.0",+ "author": {"name": "example"},+ "scopes": ["net:example.com"],+ "contributes": {"hooks": [{"key": "summarize", "name": "Summarize",+ "description": "` + wanted + `",+ "triggers": ["agent"], "transport": {"type": "http", "url": "https://example.com/s"}}]}+ }`),+ }+ manifest, err := ParseInstallationManifest(installation)+ if err != nil {+ t.Fatalf("parse manifest: %v", err)+ }+ if got := manifest.Contributes.Hooks[0].Description; got != wanted {+ t.Fatalf("description = %q, want the manifest text verbatim", got)+ }+}diff --git a/server/internal/service/plugin_hook.go b/server/internal/service/plugin_hook.goindex b494287097..0b7b5ea4be 100644--- a/server/internal/service/plugin_hook.go+++ b/server/internal/service/plugin_hook.go@@ -116,6 +116,16 @@ type hookRequestBody struct {IssueID string `json:"issue_id,omitempty"`Actor hookRequestActor `json:"actor"`Input json.RawMessage `json:"input,omitempty"`+ // Config is the installation's non-secret configuration, the values an+ // administrator typed into the host-rendered form. Sent because the handler+ // has no other way to read them — the Action API deliberately has no config+ // endpoint — and a plugin forced to keep its own second copy would make the+ // manifest's config block decorative.+ //+ // Secret-typed fields are NEVER included. They are the plugin's credentials+ // for ITS OWN services; it already has them, and putting them on the wire+ // would hand every value to whoever holds the endpoint.+ Config map[string]any `json:"config,omitempty"`// CallbackToken lets the handler call the Action API back for the few// minutes it is valid. Narrower than the installation's own token and tied// to this one call, so a handler that leaks it leaks a few minutes of the@@ -312,6 +322,38 @@ func (s *PluginService) callHookEndpoint(ctx context.Context, invocation HookInvreturn json.RawMessage(payload), nil}+// nonSecretConfig reads the installation's stored configuration and drops+// anything the manifest declared as a secret.+//+// Filtered against the MANIFEST rather than against the stored shape: secrets+// live in their own table and should never appear in the config column at all,+// so this is the check that would catch it if one ever did.+func nonSecretConfig(installation db.PluginInstallation) map[string]any {+ if len(installation.Config) == 0 {+ return nil+ }+ values := map[string]any{}+ if err := json.Unmarshal(installation.Config, &values); err != nil {+ return nil+ }+ manifest, err := ParseInstallationManifest(installation)+ if err != nil {+ // Without a manifest there is no way to tell which keys are secret, so+ // send none of them.+ return nil+ }+ for key := range values {+ field, declared := manifest.Config.Field(key)+ if !declared || field.Type == plugincontract.ConfigSecret {+ delete(values, key)+ }+ }+ if len(values) == 0 {+ return nil+ }+ return values+}+func (s *PluginService) buildHookBody(ctx context.Context, invocation HookInvocation) (hookRequestBody, error) {body := hookRequestBody{Version: 1,@@ -325,6 +367,7 @@ func (s *PluginService) buildHookBody(ctx context.Context, invocation HookInvocaif invocation.IssueID.Valid {body.IssueID = uuidString(invocation.IssueID)}+ body.Config = nonSecretConfig(invocation.Installation)if invocation.Input != nil {encoded, err := json.Marshal(invocation.Input)if err != nil {diff --git a/server/internal/service/plugin_mcp_transport.go b/server/internal/service/plugin_mcp_transport.gonew file mode 100644index 0000000000..d7d8e6e4e9--- /dev/null+++ b/server/internal/service/plugin_mcp_transport.go@@ -0,0 +1,301 @@+package service++import (+ "context"+ "encoding/json"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/plugincontract"+ "github.com/multica-ai/multica/server/pkg/remotemcp"+)++// The `mcp` transport: a hook that points at an MCP server the plugin author+// already runs, whose tools Multica adopts.+//+// The whole difference from an `http` hook is who decides the shape. An http+// hook declares one endpoint in a manifest an administrator read and approved.+// An MCP server decides its own tool list at runtime and may change it whenever+// it likes — so "install this plugin" would otherwise be a standing grant to run+// whatever that server offers next week.+//+// Hence the approval: an administrator sees the discovered tools and pins them+// by name and schema digest. A tool that appears later is not adopted; a tool+// whose schema drifts stops being called. The daemon-side enforcement already+// exists — validatePinnedRemoteMCPTools refuses at broker startup — so this+// wires the plugin's hook into the connection shape that check already reads.++// PluginMCPApproval is one hook's approved tool list.+type PluginMCPApproval struct {+ Tools []remotemcp.Tool `json:"tools"`+ ApprovedAt string `json:"approved_at"`+ ApprovedBy string `json:"approved_by,omitempty"`+}++// PluginMCPApprovals maps hook key to its approval.+type PluginMCPApprovals map[string]PluginMCPApproval++func decodeMCPApprovals(raw []byte) PluginMCPApprovals {+ approvals := PluginMCPApprovals{}+ if len(raw) > 0 {+ _ = json.Unmarshal(raw, &approvals)+ }+ return approvals+}++// DiscoverMCPHookTools asks the hook's MCP server what it offers.+//+// Read-only and admin-driven: nothing is adopted by discovering it. The+// administrator picks from this and approves, which is the step that makes a+// tool callable.+func (s *PluginService) DiscoverMCPHookTools(ctx context.Context, installation db.PluginInstallation, hookKey string) ([]remotemcp.Tool, error) {+ hook, err := FindHook(installation, hookKey)+ if err != nil {+ return nil, err+ }+ if hook.Transport.Type != plugincontract.TransportMCP {+ return nil, pluginErrf(PluginErrorInvalid, "hook %q is not an mcp transport", hookKey)+ }+ // Second layer. Manifest validation already refuses a hook whose transport+ // URL is not covered by a declared net: scope, so this is unreachable for a+ // manifest that installed cleanly — kept because the destination check below+ // takes its allow-list from here, and an empty one must fail closed rather+ // than read as "no restriction".+ domains := plugincontract.NetDomains(decodeScopes(installation.GrantedScopes))+ if len(domains) == 0 {+ return nil, pluginErrf(PluginErrorForbidden, "this Plugin was granted no net: scope, so it cannot reach an MCP server")+ }++ headers, err := s.mcpCredentialHeaders(ctx, installation, hook)+ if err != nil {+ return nil, err+ }+ // Same endpoint guard as every other outbound call: the destination must be+ // inside the consented `net:` set and resolve publicly.+ tools, _, err := remotemcp.Discover(ctx, hook.Transport.URL, domains, nil, headers)+ if err != nil {+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "could not reach the Plugin's MCP server", Err: err}+ }+ return tools, nil+}++// ApproveMCPHookTools pins a tool list for one hook.+//+// Pinned by digest, not just by name: a server that keeps a tool's name and+// changes its arguments has changed what the agent is calling, and the agent+// would have no way to notice.+func (s *PluginService) ApproveMCPHookTools(ctx context.Context, installation db.PluginInstallation, hookKey string, names []string, userID pgtype.UUID) (db.PluginInstallation, error) {+ discovered, err := s.DiscoverMCPHookTools(ctx, installation, hookKey)+ if err != nil {+ return db.PluginInstallation{}, err+ }+ byName := make(map[string]remotemcp.Tool, len(discovered))+ for _, tool := range discovered {+ byName[tool.Name] = tool+ }++ approved := make([]remotemcp.Tool, 0, len(names))+ for _, name := range names {+ tool, ok := byName[name]+ if !ok {+ // Approving something the server does not currently offer would pin+ // a name with no schema behind it, and the broker would refuse the+ // whole connection at startup.+ return db.PluginInstallation{}, pluginErrf(PluginErrorInvalid, "tool %q is not offered by this MCP server", name)+ }+ approved = append(approved, tool)+ }++ approvals := decodeMCPApprovals(installation.McpApprovals)+ if len(approved) == 0 {+ // Approving nothing is how an administrator withdraws a hook, so it+ // removes the entry rather than storing an empty allow-list that reads+ // like "approved, with nothing in it".+ delete(approvals, hookKey)+ } else {+ approvals[hookKey] = PluginMCPApproval{+ Tools: approved,+ ApprovedAt: time.Now().UTC().Format(time.RFC3339),+ ApprovedBy: uuidString(userID),+ }+ }++ encoded, err := json.Marshal(approvals)+ if err != nil {+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorInvalid, Message: "encode approvals", Err: err}+ }+ updated, err := s.Queries.SetPluginMCPApprovals(ctx, db.SetPluginMCPApprovalsParams{+ ID: installation.ID,+ McpApprovals: encoded,+ })+ if err != nil {+ return db.PluginInstallation{}, &PluginError{Kind: PluginErrorUnavailable, Message: "store approvals", Err: err}+ }+ return updated, nil+}++// AgentMCPConnections turns approved mcp hooks into broker connections.+//+// Returned in the claim payload beside the http-transport tools, so the daemon+// handles both through the machinery it already has: the existing broker proxies+// to the MCP server and validatePinnedRemoteMCPTools refuses to start if an+// approved tool went missing or its schema drifted.+//+// A hook with no approval yields no connection. That is the point — installing+// the plugin is not the grant, approving the tools is.+func (s *PluginService) AgentMCPConnections(ctx context.Context, workspaceID pgtype.UUID) ([]remotemcp.Connection, error) {+ installations, err := s.Queries.ListWorkspacePluginInstallations(ctx, workspaceID)+ if err != nil {+ return nil, &PluginError{Kind: PluginErrorUnavailable, Message: "list plugin installations", Err: err}+ }++ connections := make([]remotemcp.Connection, 0)+ for _, installation := range installations {+ if !installation.Enabled {+ continue+ }+ connections = append(connections, mcpConnectionsFor(installation)...)+ }+ return connections, nil+}++// mcpConnectionsFor turns one installation's approved mcp hooks into broker+// connections. Separated from the workspace query so the three conditions that+// decide whether a hook is offered at all — mcp transport, agent trigger, a+// non-empty approval — are testable without a database.+func mcpConnectionsFor(installation db.PluginInstallation) []remotemcp.Connection {+ manifest, err := ParseInstallationManifest(installation)+ if err != nil {+ // One unreadable manifest must not hide every other plugin's tools.+ return nil+ }+ approvals := decodeMCPApprovals(installation.McpApprovals)+ domains := plugincontract.NetDomains(decodeScopes(installation.GrantedScopes))++ connections := make([]remotemcp.Connection, 0)+ for _, hook := range manifest.Contributes.Hooks {+ if hook.Transport.Type != plugincontract.TransportMCP {+ continue+ }+ if !HookAllowsTrigger(hook, plugincontract.TriggerAgent) {+ continue+ }+ approval, ok := approvals[hook.Key]+ if !ok || len(approval.Tools) == 0 {+ continue+ }+ credentialHeader := ""+ if field, found := manifest.Config.Field(hook.Key + "_credential"); found && field.Type == plugincontract.ConfigSecret {+ credentialHeader = "Authorization"+ }+ connections = append(connections, remotemcp.Connection{+ InstallationID: uuidString(installation.ID),+ ContributionID: remotemcp.PluginContributionPrefix + uuidString(installation.ID) + ":" + hook.Key,+ ContributionKey: PluginToolName(manifest.Key, hook.Key),+ Endpoint: hook.Transport.URL,+ Transport: "http",+ // The same exact-host set the consent screen showed. The broker+ // re-checks it at dial, so a manifest that later repoints its own+ // hook still cannot reach anywhere new.+ EndpointAllowedHosts: domains,+ CredentialHeader: credentialHeader,+ ApprovedTools: approval.Tools,+ ToolSchemaDigest: toolSetDigest(approval.Tools),+ // A plugin's MCP server going down must not fail the task, for the+ // same reason a failing http hook is a tool error: an agent should+ // still be able to work on the issue.+ FailurePolicy: "optional",+ })+ }+ return connections+}++// toolSetDigest pins the whole approved set, not just each tool. A digest error+// yields the empty string: the broker then treats the set as unpinned at the+// set level while still checking every tool individually, which is the+// degradation that fails safe.+func toolSetDigest(tools []remotemcp.Tool) string {+ digest, err := remotemcp.ToolSetDigest(tools)+ if err != nil {+ return ""+ }+ return digest+}++// mcpCredentialHeaders builds the auth header from the installation's secret+// config, if the manifest declared one for this hook.+//+// Reuses the existing secret storage — write-only, secretbox-encrypted, never+// echoed by any read endpoint — rather than introducing a second place where a+// plugin's credentials live.+func (s *PluginService) mcpCredentialHeaders(ctx context.Context, installation db.PluginInstallation, hook plugincontract.Hook) (map[string][]string, error) {+ manifest, err := ParseInstallationManifest(installation)+ if err != nil {+ return nil, err+ }+ field, ok := manifest.Config.Field(hook.Key + "_credential")+ if !ok || field.Type != plugincontract.ConfigSecret {+ return nil, nil+ }+ secret, err := s.decryptedSecret(ctx, installation.ID, hook.Key+"_credential")+ if err != nil || secret == "" {+ // A declared-but-unset credential is a configuration gap, not a reason+ // to fail discovery with a confusing transport error.+ return nil, nil+ }+ return map[string][]string{"Authorization": {secret}}, nil+}++// decryptedSecret opens one stored secret.+//+// The only place a plugin secret is ever decrypted for use, and it is used+// here to authenticate to the plugin author's OWN server — never echoed back+// through any read endpoint, which is the rule the separate secret table+// exists to make structural.+func (s *PluginService) decryptedSecret(ctx context.Context, installationID pgtype.UUID, key string) (string, error) {+ if s.Secrets == nil {+ return "", pluginErrf(PluginErrorUnavailable, "plugin secrets are disabled: MULTICA_PLUGIN_SECRET_KEY is not configured")+ }+ row, err := s.Queries.GetPluginSecret(ctx, db.GetPluginSecretParams{InstallationID: installationID, Key: key})+ if err != nil {+ return "", err+ }+ plaintext, err := s.Secrets.Open(row.Ciphertext)+ if err != nil {+ return "", err+ }+ return string(plaintext), nil+}++// ApprovedMCPTools is the pinned set for one hook, by name.+func (s *PluginService) ApprovedMCPTools(installation db.PluginInstallation, hookKey string) map[string]remotemcp.Tool {+ approval, ok := decodeMCPApprovals(installation.McpApprovals)[hookKey]+ if !ok {+ return map[string]remotemcp.Tool{}+ }+ byName := make(map[string]remotemcp.Tool, len(approval.Tools))+ for _, tool := range approval.Tools {+ byName[tool.Name] = tool+ }+ return byName+}++// MCPHookCredential resolves the credential for one mcp hook, for the daemon's+// broker. Returns empty strings when the manifest declared none.+func (s *PluginService) MCPHookCredential(ctx context.Context, installation db.PluginInstallation, hookKey string) (string, string, error) {+ hook, err := FindHook(installation, hookKey)+ if err != nil {+ return "", "", err+ }+ headers, err := s.mcpCredentialHeaders(ctx, installation, hook)+ if err != nil {+ return "", "", err+ }+ for name, values := range headers {+ if len(values) > 0 {+ return name, values[0], nil+ }+ }+ return "", "", nil+}diff --git a/server/internal/service/plugin_mcp_transport_test.go b/server/internal/service/plugin_mcp_transport_test.gonew file mode 100644index 0000000000..db6a5ec25c--- /dev/null+++ b/server/internal/service/plugin_mcp_transport_test.go@@ -0,0 +1,191 @@+package service++import (+ "encoding/json"+ "testing"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/remotemcp"+)++// The approval is the grant, not the install.+//+// An http hook declares one endpoint in a manifest an administrator read. An+// MCP server decides its own tool list at runtime, so without a pinned approval+// "install this plugin" would be standing permission to run whatever that+// server offers next week.++const mcpHookManifest = `{+ "manifest_version": 1,+ "key": "com.example.mcp",+ "name": "MCP Plugin",+ "description": "d",+ "version": "1.0.0",+ "author": {"name": "example"},+ "scopes": ["issues:read", "net:tools.example.com"],+ "contributes": {"hooks": [{+ "key": "toolbox",+ "name": "Toolbox",+ "description": "Tools from an external MCP server.",+ "triggers": ["agent"],+ "transport": {"type": "mcp", "url": "https://tools.example.com/mcp"}+ }]}+}`++func mcpInstallation(t *testing.T, approvals string) db.PluginInstallation {+ t.Helper()+ if approvals == "" {+ approvals = "{}"+ }+ return db.PluginInstallation{+ ID: testInstallationID(t),+ WorkspaceID: testInstallationID(t),+ Enabled: true,+ Manifest: []byte(mcpHookManifest),+ GrantedScopes: []byte(`["issues:read","net:tools.example.com"]`),+ McpApprovals: []byte(approvals),+ }+}++// No approval, no connection. This is the whole safety property: an installed+// mcp hook is inert until an administrator pins its tools, so the plugin being+// installed and enabled is not by itself permission for an agent to call+// anything that server offers.+func TestUnapprovedMCPHookYieldsNoConnection(t *testing.T) {+ installation := mcpInstallation(t, "{}")++ if tools := (&PluginService{}).ApprovedMCPTools(installation, "toolbox"); len(tools) != 0 {+ t.Fatalf("an unapproved hook reported approved tools: %v", tools)+ }+ if connections := mcpConnectionsFor(installation); len(connections) != 0 {+ t.Fatalf("an unapproved hook produced %d connections, want none", len(connections))+ }++ // An approval that exists but is empty is a withdrawal, not an allow-all.+ withdrawn := mcpInstallation(t, `{"toolbox":{"tools":[]}}`)+ if connections := mcpConnectionsFor(withdrawn); len(connections) != 0 {+ t.Fatalf("a withdrawn hook produced %d connections, want none", len(connections))+ }+}++// An approved hook reaches the daemon as an ordinary broker connection, pinned+// to its approved tools and to the exact hosts the consent screen showed.+func TestApprovedMCPHookBecomesABrokerConnection(t *testing.T) {+ approvals, err := json.Marshal(PluginMCPApprovals{+ "toolbox": {Tools: []remotemcp.Tool{{Name: "search", SchemaDigest: "sha256:aaa"}}},+ })+ if err != nil {+ t.Fatalf("marshal approvals: %v", err)+ }+ connections := mcpConnectionsFor(mcpInstallation(t, string(approvals)))+ if len(connections) != 1 {+ t.Fatalf("got %d connections, want exactly one", len(connections))+ }++ connection := connections[0]+ if len(connection.ApprovedTools) != 1 || connection.ApprovedTools[0].Name != "search" {+ t.Fatalf("approved tools = %v, want the pinned set", connection.ApprovedTools)+ }+ if len(connection.EndpointAllowedHosts) != 1 || connection.EndpointAllowedHosts[0] != "tools.example.com" {+ t.Fatalf("allowed hosts = %v, want the granted net: scope", connection.EndpointAllowedHosts)+ }+ // A plugin's MCP server going down must not fail somebody's task.+ if connection.FailurePolicy != "optional" {+ t.Fatalf("failure policy = %q, want optional", connection.FailurePolicy)+ }+ // The daemon asks for the credential at dial time using this id, so it has+ // to name both halves or the server cannot tell which hook it means.+ want := remotemcp.PluginContributionPrefix + uuidString(mcpInstallation(t, "{}").ID) + ":toolbox"+ if connection.ContributionID != want {+ t.Fatalf("contribution id = %q, want %q", connection.ContributionID, want)+ }+}++// An approved hook carries its pinned set, and the digest travels with it —+// the broker's validatePinnedRemoteMCPTools compares against exactly this.+func TestApprovedMCPToolsArePinnedByDigest(t *testing.T) {+ approvals, err := json.Marshal(PluginMCPApprovals{+ "toolbox": {Tools: []remotemcp.Tool{+ {Name: "search", SchemaDigest: "sha256:aaa"},+ {Name: "fetch", SchemaDigest: "sha256:bbb"},+ }},+ })+ if err != nil {+ t.Fatalf("marshal approvals: %v", err)+ }+ installation := mcpInstallation(t, string(approvals))++ pinned := (&PluginService{}).ApprovedMCPTools(installation, "toolbox")+ if len(pinned) != 2 {+ t.Fatalf("pinned = %v, want two tools", pinned)+ }+ if pinned["search"].SchemaDigest != "sha256:aaa" {+ t.Fatalf("the digest must survive storage, got %q", pinned["search"].SchemaDigest)+ }++ // A name-only pin would let a server keep a tool's name and change its+ // arguments without the agent noticing, which is what the digest prevents.+ drifted := []remotemcp.Tool{{Name: "search", SchemaDigest: "sha256:CHANGED"}}+ if err := validatePinnedAgainst(pinned, drifted); err == nil {+ t.Fatal("a drifted schema must not pass the pin")+ }+}++// validatePinnedAgainst mirrors the daemon's broker check closely enough to+// assert the property here; the broker's own copy is what runs in production.+func validatePinnedAgainst(pinned map[string]remotemcp.Tool, discovered []remotemcp.Tool) error {+ available := map[string]remotemcp.Tool{}+ for _, tool := range discovered {+ available[tool.Name] = tool+ }+ for name, tool := range pinned {+ current, ok := available[name]+ if !ok {+ continue+ }+ if current.SchemaDigest != tool.SchemaDigest {+ return errSchemaDrift+ }+ }+ return nil+}++var errSchemaDrift = &PluginError{Kind: PluginErrorConflict, Message: "schema drifted"}++// A hook that did not declare the agent trigger is not adopted even once its+// tools are approved: approval says which tools, the trigger says whether an+// agent may reach them at all.+func TestMCPConnectionRequiresTheAgentTrigger(t *testing.T) {+ manifest := `{+ "manifest_version": 1,+ "key": "com.example.mcp2",+ "name": "MCP Plugin",+ "description": "d",+ "version": "1.0.0",+ "author": {"name": "example"},+ "scopes": ["net:tools.example.com"],+ "contributes": {"hooks": [{+ "key": "toolbox", "name": "Toolbox", "description": "Not for agents.",+ "triggers": ["manual"],+ "transport": {"type": "mcp", "url": "https://tools.example.com/mcp"}+ }]}+ }`+ installation := db.PluginInstallation{+ ID: testInstallationID(t), Enabled: true,+ Manifest: []byte(manifest),+ GrantedScopes: []byte(`["net:tools.example.com"]`),+ }+ parsed, err := ParseInstallationManifest(installation)+ if err != nil {+ t.Fatalf("parse: %v", err)+ }+ if HookAllowsTrigger(parsed.Contributes.Hooks[0], "agent") {+ t.Fatal("a manual-only hook must not be reachable by an agent")+ }++ // Even with its tools approved, it is not offered to an agent.+ installation.McpApprovals = []byte(`{"toolbox":{"tools":[{"name":"search"}]}}`)+ if connections := mcpConnectionsFor(installation); len(connections) != 0 {+ t.Fatalf("a manual-only hook produced %d connections, want none", len(connections))+ }+}diff --git a/server/internal/service/plugin_skill.go b/server/internal/service/plugin_skill.gonew file mode 100644index 0000000000..be5ab91e4e--- /dev/null+++ b/server/internal/service/plugin_skill.go@@ -0,0 +1,139 @@+package service++import (+ "context"+ "net/url"+ "strings"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/skill"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/plugincontract"+)++// Skill resources.+//+// A plugin's `skill` resource becomes an ordinary row in the existing skill+// table. Not a plugin-owned copy, not a bundle, not an artifact with a digest:+// the previous plugin system built all of that across fourteen tables and, at+// the end of it, delivered one SKILL.md that this table could already hold.+//+// The only thing the platform has to remember is which installation contributed+// which skill, so uninstall removes exactly those and nothing a person wrote.+// That is one nullable column.+//+// A resource is not a hook — nothing calls anything. The file is fetched once,+// at install, from the same origin as the manifest, and after that it is just a+// skill.++// maxSkillBytes bounds one fetched SKILL.md. Generous for prose, small enough+// that a source URL cannot use the install path to push a large body into the+// database.+const maxSkillBytes = 256 * 1024++// InstallSkillResources writes the manifest's skill resources and prunes the+// ones this installation no longer declares.+//+// Called inside the install transaction: a plugin that half-installs its skills+// is worse than one that fails, because the missing half is invisible.+func (s *PluginService) InstallSkillResources(ctx context.Context, queries *db.Queries, installation db.PluginInstallation, manifest plugincontract.Manifest, sourceURL string, userID pgtype.UUID) error {+ resources := skillResources(manifest)++ // Prune first, so a rename frees its old name before the new one is+ // written. The reverse order would collide with the table's unique+ // (workspace_id, name) on any rename that only changes case or spacing.+ keep := make([]string, 0, len(resources))+ for _, resource := range resources {+ keep = append(keep, resource.Key)+ }+ if err := queries.DeletePluginSkillsNotIn(ctx, db.DeletePluginSkillsNotInParams{+ PluginInstallationID: installation.ID,+ KeepNames: keep,+ }); err != nil {+ return &PluginError{Kind: PluginErrorUnavailable, Message: "prune plugin skills", Err: err}+ }+ if len(resources) == 0 {+ return nil+ }++ for _, resource := range resources {+ content, err := s.fetchSkillResource(ctx, sourceURL, resource.Entry)+ if err != nil {+ return err+ }+ name, description := skill.ParseSkillFrontmatter(content)+ // The manifest key is authoritative for the name, not the frontmatter.+ // The consent screen listed the key, the tool namespace uses it, and a+ // file that disagrees must not silently install under another name.+ name = resource.Key+ if strings.TrimSpace(description) == "" {+ description = "Provided by the " + manifest.Name + " Plugin."+ }++ if _, err := queries.UpsertPluginSkill(ctx, db.UpsertPluginSkillParams{+ WorkspaceID: installation.WorkspaceID,+ Name: name,+ Description: description,+ Content: content,+ CreatedBy: userID,+ PluginInstallationID: installation.ID,+ }); err != nil {+ if isUniqueViolation(err) {+ return pluginErrf(PluginErrorConflict,+ "a skill named %q already exists in this workspace", name)+ }+ return &PluginError{Kind: PluginErrorUnavailable, Message: "install plugin skill", Err: err}+ }+ }+ return nil+}++func skillResources(manifest plugincontract.Manifest) []plugincontract.Resource {+ resources := make([]plugincontract.Resource, 0, len(manifest.Contributes.Resources))+ for _, resource := range manifest.Contributes.Resources {+ if resource.Type == plugincontract.ResourceSkill {+ resources = append(resources, resource)+ }+ }+ return resources+}++// fetchSkillResource reads one SKILL.md from beside the manifest.+//+// Resolved relative to the source URL rather than taken as a URL of its own:+// the manifest already passed the origin checks, and letting a resource name an+// arbitrary address would hand the install path a second, unreviewed fetch+// target. `entry` is validated at parse time to be a relative path with no+// traversal, which is what makes this safe to join.+func (s *PluginService) fetchSkillResource(ctx context.Context, sourceURL, entry string) (string, error) {+ if strings.HasPrefix(sourceURL, LocalSourcePrefix) {+ raw, err := s.readLocalFile(strings.TrimPrefix(sourceURL, LocalSourcePrefix), entry)+ if err != nil {+ return "", err+ }+ return string(raw), nil+ }++ base, err := url.Parse(sourceURL)+ if err != nil {+ return "", pluginErrf(PluginErrorInvalid, "source_url is not a valid URL")+ }+ resolved := base.JoinPath("..", entry).String()++ var raw []byte+ if s.isDevOrigin(resolved) {+ raw, err = fetchDevManifest(ctx, resolved)+ } else {+ raw, err = fetchRemoteManifest(ctx, resolved)+ }+ if err != nil {+ return "", &PluginError{Kind: PluginErrorInvalid, Message: "fetch plugin skill " + entry, Err: err}+ }+ if len(raw) > maxSkillBytes {+ return "", pluginErrf(PluginErrorInvalid, "plugin skill %s exceeds %d bytes", entry, maxSkillBytes)+ }+ if strings.TrimSpace(string(raw)) == "" {+ return "", pluginErrf(PluginErrorInvalid, "plugin skill %s is empty", entry)+ }+ return string(raw), nil+}diff --git a/server/internal/service/plugin_test.go b/server/internal/service/plugin_test.goindex f0f1c1fb6f..ad518b561a 100644--- a/server/internal/service/plugin_test.go+++ b/server/internal/service/plugin_test.go@@ -305,28 +305,29 @@ func TestShippedHostCapabilitiesRunTheSurfacesTheHostMounts(t *testing.T) {}// handler.InvokePluginHook serves ui and manual; service.PluginEventDispatcher- // serves event off the internal bus.- for _, trigger := range []string{plugincontract.TriggerUI, plugincontract.TriggerManual, plugincontract.TriggerEvent} {+ // serves event off the internal bus; daemon/plugin_hook_mcp.go renders+ // agent-trigger hooks as MCP tools.+ for _, trigger := range []string{+ plugincontract.TriggerUI, plugincontract.TriggerManual,+ plugincontract.TriggerEvent, plugincontract.TriggerAgent,+ } {if !shipped.HookTriggers[trigger] {t.Fatalf("hook trigger %q has a host call site and must be shipped", trigger)}}- // The agent trigger is not a call site the host drives — it is a hook- // exposed to an agent as an MCP tool, which needs the daemon-side server.- if shipped.HookTriggers[plugincontract.TriggerAgent] {- t.Fatal("the agent trigger needs the daemon-side MCP server, which has not landed")- }- // service.callHookEndpoint speaks http and nothing else.- if !shipped.HookTransport[plugincontract.TransportHTTP] {- t.Fatal("the http transport is implemented by callHookEndpoint and must be shipped")- }- if shipped.HookTransport[plugincontract.TransportMCP] {- t.Fatal("the mcp transport has no implementation yet")+ // service.callHookEndpoint speaks http; service.AgentMCPConnections turns an+ // approved mcp hook into a broker connection.+ for _, transport := range []string{plugincontract.TransportHTTP, plugincontract.TransportMCP} {+ if !shipped.HookTransport[transport] {+ t.Fatalf("hook transport %q has an implementation and must be shipped", transport)+ }}- if shipped.ResourceTypes[plugincontract.ResourceSkill] {- t.Fatal("skill resources are enabled but the agent integration has not landed")+ // service.InstallSkillResources writes these into the skill table, and+ // Uninstall removes them again.+ if !shipped.ResourceTypes[plugincontract.ResourceSkill] {+ t.Fatal("skill resources are installed by InstallSkillResources and must be shipped")}}diff --git a/server/migrations/368_skill_plugin_ownership.down.sql b/server/migrations/368_skill_plugin_ownership.down.sqlnew file mode 100644index 0000000000..0c0e7686fa--- /dev/null+++ b/server/migrations/368_skill_plugin_ownership.down.sql@@ -0,0 +1 @@+ALTER TABLE skill DROP COLUMN IF EXISTS plugin_installation_id;diff --git a/server/migrations/368_skill_plugin_ownership.up.sql b/server/migrations/368_skill_plugin_ownership.up.sqlnew file mode 100644index 0000000000..34e4101c44--- /dev/null+++ b/server/migrations/368_skill_plugin_ownership.up.sql@@ -0,0 +1,16 @@+-- A plugin's `skill` resources become ordinary workspace skills.+--+-- Deliberately the EXISTING skill table rather than a plugin-owned copy. The+-- previous plugin system routed skills through an artifact/digest/bundle+-- pipeline across fourteen tables and, after all of it, delivered one SKILL.md+-- that the skill table could already hold. A plugin skill is a skill; the only+-- thing the platform needs to remember is who put it there.+--+-- That is what this column is for: uninstall has to remove exactly the skills+-- the installation contributed, and nothing a person wrote by hand. NULL means+-- a human made it, which is every row that exists today.+--+-- Nullable, no default: metadata-only, no rewrite. No FK per repository policy —+-- uninstall deletes these explicitly, in the same transaction as the rest of the+-- installation's cleanup.+ALTER TABLE skill ADD COLUMN IF NOT EXISTS plugin_installation_id UUID;diff --git a/server/migrations/369_plugin_mcp_approvals.down.sql b/server/migrations/369_plugin_mcp_approvals.down.sqlnew file mode 100644index 0000000000..ed42636464--- /dev/null+++ b/server/migrations/369_plugin_mcp_approvals.down.sql@@ -0,0 +1 @@+ALTER TABLE plugin_installation DROP COLUMN IF EXISTS mcp_approvals;diff --git a/server/migrations/369_plugin_mcp_approvals.up.sql b/server/migrations/369_plugin_mcp_approvals.up.sqlnew file mode 100644index 0000000000..0c20f3f104--- /dev/null+++ b/server/migrations/369_plugin_mcp_approvals.up.sql@@ -0,0 +1,25 @@+-- Admin approval for an mcp-transport hook's tool list.+--+-- A hook with transport.type == "mcp" points at an MCP server the plugin author+-- already runs, and Multica adopts its tools as callable hooks. Unlike an http+-- hook — where the manifest declares exactly one endpoint and one shape — an MCP+-- server decides its own tool list at runtime and can change it whenever it+-- likes.+--+-- That is the difference this column exists for. An administrator approves a+-- specific list with a specific schema digest; a tool that appears later is not+-- adopted, and a tool whose schema drifts stops being called. Without the pin,+-- "install this plugin" would be a standing grant to run whatever that server+-- decides to offer next week.+--+-- Keyed by hook key, so one installation can contribute several mcp hooks and+-- each is approved on its own:+-- {"<hook_key>": {"tools": [{"name": ..., "schema_digest": ...}],+-- "approved_at": "...", "approved_by": "<user uuid>"}}+--+-- JSONB rather than a table: nothing joins on it, nothing queries inside it, and+-- it is read as a whole whenever the installation is. A table would be a second+-- lifecycle to keep in step with the installation for no reader's benefit.+ALTER TABLE plugin_installation+ ADD COLUMN IF NOT EXISTS mcp_approvals JSONB NOT NULL DEFAULT '{}'::jsonb+ CHECK (jsonb_typeof(mcp_approvals) = 'object');diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex bbed8506cf..61f6e8ffb7 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -955,6 +955,7 @@ type PluginInstallation struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`TokenHash pgtype.Text `json:"token_hash"`TokenRotatedAt pgtype.Timestamptz `json:"token_rotated_at"`+ McpApprovals []byte `json:"mcp_approvals"`}type PluginInvocation struct {@@ -1053,15 +1054,16 @@ type RuntimeProfile struct {}type Skill struct {- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- Name string `json:"name"`- Description string `json:"description"`- Content string `json:"content"`- Config []byte `json:"config"`- CreatedBy pgtype.UUID `json:"created_by"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Name string `json:"name"`+ Description string `json:"description"`+ Content string `json:"content"`+ Config []byte `json:"config"`+ CreatedBy pgtype.UUID `json:"created_by"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ PluginInstallationID pgtype.UUID `json:"plugin_installation_id"`}type SkillFile struct {diff --git a/server/pkg/db/generated/plugin.sql.go b/server/pkg/db/generated/plugin.sql.goindex ce35467298..87c74a9f58 100644--- a/server/pkg/db/generated/plugin.sql.go+++ b/server/pkg/db/generated/plugin.sql.go@@ -55,7 +55,7 @@ const createPluginInstallation = `-- name: CreatePluginInstallation :oneINSERT INTO plugin_installation (workspace_id, plugin_key, source_url, version, manifest, granted_scopes, installed_by) VALUES ($1, $2, $3, $4, $5, $6, $7)-RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at+RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals`type CreatePluginInstallationParams struct {@@ -94,6 +94,7 @@ func (q *Queries) CreatePluginInstallation(ctx context.Context, arg CreatePlugin&i.UpdatedAt,&i.TokenHash,&i.TokenRotatedAt,+ &i.McpApprovals,)return i, err}@@ -203,6 +204,32 @@ func (q *Queries) DeletePluginSecretsByInstallation(ctx context.Context, installreturn err}+const deletePluginSkillsByInstallation = `-- name: DeletePluginSkillsByInstallation :exec+DELETE FROM skill WHERE plugin_installation_id = $1+`++func (q *Queries) DeletePluginSkillsByInstallation(ctx context.Context, pluginInstallationID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deletePluginSkillsByInstallation, pluginInstallationID)+ return err+}++const deletePluginSkillsNotIn = `-- name: DeletePluginSkillsNotIn :exec+DELETE FROM skill+WHERE plugin_installation_id = $1 AND name <> ALL($2::text[])+`++type DeletePluginSkillsNotInParams struct {+ PluginInstallationID pgtype.UUID `json:"plugin_installation_id"`+ KeepNames []string `json:"keep_names"`+}++// Upgrade pruning: a skill this installation used to contribute but no longer+// declares must go, or a renamed skill leaves its predecessor behind forever.+func (q *Queries) DeletePluginSkillsNotIn(ctx context.Context, arg DeletePluginSkillsNotInParams) error {+ _, err := q.db.Exec(ctx, deletePluginSkillsNotIn, arg.PluginInstallationID, arg.KeepNames)+ return err+}+const deletePluginStorageByInstallation = `-- name: DeletePluginStorageByInstallation :execDELETE FROM plugin_storage WHERE installation_id = $1`@@ -238,7 +265,7 @@ func (q *Queries) DeletePluginStorageValue(ctx context.Context, arg DeletePlugin}const getPluginInstallation = `-- name: GetPluginInstallation :one-SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at FROM plugin_installation WHERE id = $1+SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals FROM plugin_installation WHERE id = $1`func (q *Queries) GetPluginInstallation(ctx context.Context, id pgtype.UUID) (PluginInstallation, error) {@@ -259,12 +286,13 @@ func (q *Queries) GetPluginInstallation(ctx context.Context, id pgtype.UUID) (Pl&i.UpdatedAt,&i.TokenHash,&i.TokenRotatedAt,+ &i.McpApprovals,)return i, err}const getPluginInstallationByTokenHash = `-- name: GetPluginInstallationByTokenHash :one-SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at FROM plugin_installation WHERE token_hash = $1+SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals FROM plugin_installation WHERE token_hash = $1`// Looked up by hash, so the plaintext token exists only in the caller's request.@@ -286,6 +314,7 @@ func (q *Queries) GetPluginInstallationByTokenHash(ctx context.Context, tokenHas&i.UpdatedAt,&i.TokenHash,&i.TokenRotatedAt,+ &i.McpApprovals,)return i, err}@@ -383,7 +412,7 @@ func (q *Queries) GetPluginStorageValue(ctx context.Context, arg GetPluginStorag}const getWorkspacePluginInstallation = `-- name: GetWorkspacePluginInstallation :one-SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at FROM plugin_installation+SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals FROM plugin_installationWHERE workspace_id = $1 AND id = $2`@@ -410,12 +439,13 @@ func (q *Queries) GetWorkspacePluginInstallation(ctx context.Context, arg GetWor&i.UpdatedAt,&i.TokenHash,&i.TokenRotatedAt,+ &i.McpApprovals,)return i, err}const getWorkspacePluginInstallationByKey = `-- name: GetWorkspacePluginInstallationByKey :one-SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at FROM plugin_installation+SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals FROM plugin_installationWHERE workspace_id = $1 AND plugin_key = $2`@@ -442,6 +472,7 @@ func (q *Queries) GetWorkspacePluginInstallationByKey(ctx context.Context, arg G&i.UpdatedAt,&i.TokenHash,&i.TokenRotatedAt,+ &i.McpApprovals,)return i, err}@@ -523,6 +554,41 @@ func (q *Queries) ListPluginSecretKeys(ctx context.Context, installationID pgtypreturn items, nil}+const listPluginSkills = `-- name: ListPluginSkills :many+SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id FROM skill WHERE plugin_installation_id = $1 ORDER BY name ASC+`++func (q *Queries) ListPluginSkills(ctx context.Context, pluginInstallationID pgtype.UUID) ([]Skill, error) {+ rows, err := q.db.Query(ctx, listPluginSkills, pluginInstallationID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []Skill{}+ for rows.Next() {+ var i Skill+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.Description,+ &i.Content,+ &i.Config,+ &i.CreatedBy,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.PluginInstallationID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listPluginStorageKeys = `-- name: ListPluginStorageKeys :manySELECT key, octet_length(value)::bigint AS size_bytes, updated_atFROM plugin_storage@@ -563,7 +629,7 @@ func (q *Queries) ListPluginStorageKeys(ctx context.Context, arg ListPluginStora}const listWorkspacePluginInstallations = `-- name: ListWorkspacePluginInstallations :many-SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at FROM plugin_installation+SELECT id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals FROM plugin_installationWHERE workspace_id = $1ORDER BY created_at ASC`@@ -592,6 +658,7 @@ func (q *Queries) ListWorkspacePluginInstallations(ctx context.Context, workspac&i.UpdatedAt,&i.TokenHash,&i.TokenRotatedAt,+ &i.McpApprovals,); err != nil {return nil, err}@@ -608,7 +675,7 @@ UPDATE plugin_installationSET enabled = $2,updated_at = now()WHERE id = $1-RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at+RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals`type SetPluginInstallationEnabledParams struct {@@ -634,6 +701,7 @@ func (q *Queries) SetPluginInstallationEnabled(ctx context.Context, arg SetPlugi&i.UpdatedAt,&i.TokenHash,&i.TokenRotatedAt,+ &i.McpApprovals,)return i, err}@@ -654,12 +722,47 @@ func (q *Queries) SetPluginInstallationToken(ctx context.Context, arg SetPluginIreturn err}+const setPluginMCPApprovals = `-- name: SetPluginMCPApprovals :one+UPDATE plugin_installation+SET mcp_approvals = $2, updated_at = now()+WHERE id = $1+RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals+`++type SetPluginMCPApprovalsParams struct {+ ID pgtype.UUID `json:"id"`+ McpApprovals []byte `json:"mcp_approvals"`+}++func (q *Queries) SetPluginMCPApprovals(ctx context.Context, arg SetPluginMCPApprovalsParams) (PluginInstallation, error) {+ row := q.db.QueryRow(ctx, setPluginMCPApprovals, arg.ID, arg.McpApprovals)+ var i PluginInstallation+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.PluginKey,+ &i.SourceUrl,+ &i.Version,+ &i.Manifest,+ &i.GrantedScopes,+ &i.Config,+ &i.Enabled,+ &i.InstalledBy,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.TokenHash,+ &i.TokenRotatedAt,+ &i.McpApprovals,+ )+ return i, err+}+const updatePluginInstallationConfig = `-- name: UpdatePluginInstallationConfig :oneUPDATE plugin_installationSET config = $2,updated_at = now()WHERE id = $1-RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at+RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals`type UpdatePluginInstallationConfigParams struct {@@ -685,6 +788,7 @@ func (q *Queries) UpdatePluginInstallationConfig(ctx context.Context, arg Update&i.UpdatedAt,&i.TokenHash,&i.TokenRotatedAt,+ &i.McpApprovals,)return i, err}@@ -698,7 +802,7 @@ SET source_url = $2,config = $6,updated_at = now()WHERE id = $1-RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at+RETURNING id, workspace_id, plugin_key, source_url, version, manifest, granted_scopes, config, enabled, installed_by, created_at, updated_at, token_hash, token_rotated_at, mcp_approvals`type UpdatePluginInstallationManifestParams struct {@@ -738,6 +842,7 @@ func (q *Queries) UpdatePluginInstallationManifest(ctx context.Context, arg Upda&i.UpdatedAt,&i.TokenHash,&i.TokenRotatedAt,+ &i.McpApprovals,)return i, err}@@ -760,6 +865,58 @@ func (q *Queries) UpsertPluginSecret(ctx context.Context, arg UpsertPluginSecretreturn err}+const upsertPluginSkill = `-- name: UpsertPluginSkill :one+INSERT INTO skill (workspace_id, name, description, content, config, created_by, plugin_installation_id)+VALUES ($1, $2, $3, $4, '{}'::jsonb, $6, $5)+ON CONFLICT (workspace_id, name) DO UPDATE SET+ description = EXCLUDED.description,+ content = EXCLUDED.content,+ updated_at = now()+WHERE skill.plugin_installation_id = EXCLUDED.plugin_installation_id+RETURNING id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id+`++type UpsertPluginSkillParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Name string `json:"name"`+ Description string `json:"description"`+ Content string `json:"content"`+ PluginInstallationID pgtype.UUID `json:"plugin_installation_id"`+ CreatedBy pgtype.UUID `json:"created_by"`+}++// A plugin's skill resource, as an ordinary workspace skill.+//+// Upsert on (workspace_id, name) because that is the table's own uniqueness+// rule and an upgrade re-installs the same skill. The WHERE clause is the+// important half: it refuses to overwrite a skill a PERSON created, or one+// another installation owns. A plugin claiming a name someone already used must+// fail the install loudly, not silently replace their work.+func (q *Queries) UpsertPluginSkill(ctx context.Context, arg UpsertPluginSkillParams) (Skill, error) {+ row := q.db.QueryRow(ctx, upsertPluginSkill,+ arg.WorkspaceID,+ arg.Name,+ arg.Description,+ arg.Content,+ arg.PluginInstallationID,+ arg.CreatedBy,+ )+ var i Skill+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.Description,+ &i.Content,+ &i.Config,+ &i.CreatedBy,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.PluginInstallationID,+ )+ return i, err+}+const upsertPluginStorageValue = `-- name: UpsertPluginStorageValue :oneINSERT INTO plugin_storage (installation_id, scope_type, scope_id, key, value)VALUES ($1, $2, $3, $4, $5)diff --git a/server/pkg/db/generated/skill.sql.go b/server/pkg/db/generated/skill.sql.goindex 7ae18119cd..b9ab06cb4b 100644--- a/server/pkg/db/generated/skill.sql.go+++ b/server/pkg/db/generated/skill.sql.go@@ -30,7 +30,7 @@ func (q *Queries) AddAgentSkill(ctx context.Context, arg AddAgentSkillParams) erconst createSkill = `-- name: CreateSkill :oneINSERT INTO skill (workspace_id, name, description, content, config, created_by)VALUES ($1, $2, $3, $4, $5, $6)-RETURNING id, workspace_id, name, description, content, config, created_by, created_at, updated_at+RETURNING id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id`type CreateSkillParams struct {@@ -62,6 +62,7 @@ func (q *Queries) CreateSkill(ctx context.Context, arg CreateSkillParams) (Skill&i.CreatedBy,&i.CreatedAt,&i.UpdatedAt,+ &i.PluginInstallationID,)return i, err}@@ -100,7 +101,7 @@ func (q *Queries) DeleteSkillFilesBySkill(ctx context.Context, skillID pgtype.UU}const getSkill = `-- name: GetSkill :one-SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at FROM skill+SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id FROM skillWHERE id = $1`@@ -117,12 +118,13 @@ func (q *Queries) GetSkill(ctx context.Context, id pgtype.UUID) (Skill, error) {&i.CreatedBy,&i.CreatedAt,&i.UpdatedAt,+ &i.PluginInstallationID,)return i, err}const getSkillByWorkspaceAndName = `-- name: GetSkillByWorkspaceAndName :one-SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at FROM skill+SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id FROM skillWHERE workspace_id = $1 AND name = $2`@@ -146,6 +148,7 @@ func (q *Queries) GetSkillByWorkspaceAndName(ctx context.Context, arg GetSkillBy&i.CreatedBy,&i.CreatedAt,&i.UpdatedAt,+ &i.PluginInstallationID,)return i, err}@@ -170,7 +173,7 @@ func (q *Queries) GetSkillFile(ctx context.Context, id pgtype.UUID) (SkillFile,}const getSkillInWorkspace = `-- name: GetSkillInWorkspace :one-SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at FROM skill+SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id FROM skillWHERE id = $1 AND workspace_id = $2`@@ -192,6 +195,7 @@ func (q *Queries) GetSkillInWorkspace(ctx context.Context, arg GetSkillInWorkspa&i.CreatedBy,&i.CreatedAt,&i.UpdatedAt,+ &i.PluginInstallationID,)return i, err}@@ -284,7 +288,7 @@ func (q *Queries) ListAgentSkillSummaries(ctx context.Context, agentID pgtype.UUconst listAgentSkills = `-- name: ListAgentSkills :many-SELECT s.id, s.workspace_id, s.name, s.description, s.content, s.config, s.created_by, s.created_at, s.updated_at FROM skill s+SELECT s.id, s.workspace_id, s.name, s.description, s.content, s.config, s.created_by, s.created_at, s.updated_at, s.plugin_installation_id FROM skill sJOIN agent_skill ask ON ask.skill_id = s.idWHERE ask.agent_id = $1 AND ask.enabled = TRUEORDER BY s.name ASC@@ -310,6 +314,7 @@ func (q *Queries) ListAgentSkills(ctx context.Context, agentID pgtype.UUID) ([]S&i.CreatedBy,&i.CreatedAt,&i.UpdatedAt,+ &i.PluginInstallationID,); err != nil {return nil, err}@@ -451,7 +456,7 @@ func (q *Queries) ListSkillSummariesByWorkspace(ctx context.Context, workspaceIDconst listSkillsByWorkspace = `-- name: ListSkillsByWorkspace :many-SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at FROM skill+SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id FROM skillWHERE workspace_id = $1ORDER BY name ASC`@@ -476,6 +481,7 @@ func (q *Queries) ListSkillsByWorkspace(ctx context.Context, workspaceID pgtype.&i.CreatedBy,&i.CreatedAt,&i.UpdatedAt,+ &i.PluginInstallationID,); err != nil {return nil, err}@@ -539,7 +545,7 @@ UPDATE skill SETconfig = COALESCE($5, config),updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, description, content, config, created_by, created_at, updated_at+RETURNING id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id`type UpdateSkillParams struct {@@ -569,6 +575,7 @@ func (q *Queries) UpdateSkill(ctx context.Context, arg UpdateSkillParams) (Skill&i.CreatedBy,&i.CreatedAt,&i.UpdatedAt,+ &i.PluginInstallationID,)return i, err}diff --git a/server/pkg/db/queries/plugin.sql b/server/pkg/db/queries/plugin.sqlindex 42fe9216e4..ff3da4e001 100644--- a/server/pkg/db/queries/plugin.sql+++ b/server/pkg/db/queries/plugin.sql@@ -147,3 +147,38 @@ DELETE FROM plugin_invocation WHERE installation_id = $1;-- name: DeleteExpiredPluginInvocations :execrows-- TTL sweep. This table is operational telemetry, not history to keep.DELETE FROM plugin_invocation WHERE created_at < $1;++-- name: UpsertPluginSkill :one+-- A plugin's skill resource, as an ordinary workspace skill.+--+-- Upsert on (workspace_id, name) because that is the table's own uniqueness+-- rule and an upgrade re-installs the same skill. The WHERE clause is the+-- important half: it refuses to overwrite a skill a PERSON created, or one+-- another installation owns. A plugin claiming a name someone already used must+-- fail the install loudly, not silently replace their work.+INSERT INTO skill (workspace_id, name, description, content, config, created_by, plugin_installation_id)+VALUES ($1, $2, $3, $4, '{}'::jsonb, sqlc.narg(created_by), $5)+ON CONFLICT (workspace_id, name) DO UPDATE SET+ description = EXCLUDED.description,+ content = EXCLUDED.content,+ updated_at = now()+WHERE skill.plugin_installation_id = EXCLUDED.plugin_installation_id+RETURNING *;++-- name: ListPluginSkills :many+SELECT * FROM skill WHERE plugin_installation_id = $1 ORDER BY name ASC;++-- name: DeletePluginSkillsByInstallation :exec+DELETE FROM skill WHERE plugin_installation_id = $1;++-- name: DeletePluginSkillsNotIn :exec+-- Upgrade pruning: a skill this installation used to contribute but no longer+-- declares must go, or a renamed skill leaves its predecessor behind forever.+DELETE FROM skill+WHERE plugin_installation_id = $1 AND name <> ALL(@keep_names::text[]);++-- name: SetPluginMCPApprovals :one+UPDATE plugin_installation+SET mcp_approvals = $2, updated_at = now()+WHERE id = $1+RETURNING *;diff --git a/server/pkg/plugincontract/capabilities.go b/server/pkg/plugincontract/capabilities.goindex 36a4bf6fcc..f2cea286e7 100644--- a/server/pkg/plugincontract/capabilities.go+++ b/server/pkg/plugincontract/capabilities.go@@ -35,16 +35,24 @@ func HostCapabilities() Capabilities {SurfaceIssuePanel: true,SurfaceModal: true,},- // The agent trigger is not a fourth call site the host drives; it is a- // hook exposed to an agent as an MCP tool, which needs the daemon-side- // server that lands with the agent integration.+ // The agent trigger is not a call site the host drives: the hook is+ // offered to an agent as an MCP tool and the agent decides. The+ // daemon-side server that renders it is daemon/plugin_hook_mcp.go.HookTriggers: map[string]bool{TriggerUI: true,TriggerManual: true,TriggerEvent: true,+ TriggerAgent: true,},- HookTransport: map[string]bool{TransportHTTP: true},- ResourceTypes: map[string]bool{},+ // http calls one declared endpoint; mcp adopts an external MCP server's+ // tools, which is why it ships with an approval step that pins them by+ // schema digest — see service/plugin_mcp_transport.go. Installing the+ // plugin is not the grant there; approving the tools is.+ HookTransport: map[string]bool{TransportHTTP: true, TransportMCP: true},+ // A skill resource is not a call in either direction — it is a SKILL.md+ // written into the existing skill table at install and removed at+ // uninstall. service.InstallSkillResources does that.+ ResourceTypes: map[string]bool{ResourceSkill: true},}}diff --git a/server/pkg/remotemcp/client.go b/server/pkg/remotemcp/client.goindex 364b98692f..0a35c6a41b 100644--- a/server/pkg/remotemcp/client.go+++ b/server/pkg/remotemcp/client.go@@ -34,6 +34,16 @@ func ValidatePublicHTTPSEndpoint(ctx context.Context, raw string, allowedHosts [if err != nil {return nil, fmt.Errorf("parse endpoint: %w", err)}+ // An operator-named dev origin skips the public-internet requirement and+ // nothing else: the net: scope below still applies, so a Plugin still+ // cannot reach a destination the administrator did not consent to.+ if isDevOrigin(endpoint) {+ devHost := strings.ToLower(strings.TrimSuffix(endpoint.Hostname(), "."))+ if len(allowedHosts) > 0 && !hostAllowed(devHost, allowedHosts) {+ return nil, errors.New("endpoint host is outside the Plugin endpoint policy")+ }+ return endpoint, nil+ }if endpoint.Scheme != "https" || endpoint.Hostname() == "" || endpoint.User != nil || endpoint.Fragment != "" || endpoint.RawQuery != "" {return nil, errors.New("endpoint must be a public HTTPS URL without userinfo, query, or fragment")}@@ -102,9 +112,21 @@ func isPublicAddress(address netip.Addr) bool {}func NewSecureHTTPClient(endpoint *url.URL) *http.Client {+ // Decided once, here, rather than inside the dialer: the endpoint is fixed+ // for this client's lifetime, so a per-dial lookup could only differ if the+ // environment changed mid-task, and honouring that would be a way to widen+ // the guard after the connection was approved.+ devOrigin := isDevOrigin(endpoint)dialer := &net.Dialer{Timeout: ConnectTimeout, KeepAlive: 30 * time.Second}transport := http.DefaultTransport.(*http.Transport).Clone()transport.Proxy = nil+ if devOrigin {+ // Trust an extra CA for this origin, never skip verification: a plugin+ // author's local MCP server still presents a certificate.+ if config := devTLSConfig(); config != nil {+ transport.TLSClientConfig = config+ }+ }transport.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {host, port, err := net.SplitHostPort(address)if err != nil {@@ -119,7 +141,10 @@ func NewSecureHTTPClient(endpoint *url.URL) *http.Client {}for _, candidate := range addresses {candidate = candidate.Unmap()- if !isPublicAddress(candidate) {+ // The host pin above still holds for a dev origin, so a redirect+ // pointing somewhere else is refused either way. What this skips is+ // only "the address must be on the public internet".+ if !devOrigin && !isPublicAddress(candidate) {return nil, errors.New("remote MCP endpoint resolved to a non-public address")}connection, dialErr := dialer.DialContext(ctx, network, net.JoinHostPort(candidate.String(), port))@@ -154,6 +179,12 @@ type discoveredTool struct {InputSchema json.RawMessage `json:"inputSchema"`}+// SupportedProtocolVersions is the MCP protocol revisions this build speaks,+// most preferred first. Discover offers the first and accepts any of them.+func SupportedProtocolVersions() []string {+ return []string{"2025-03-26", "2024-11-05"}+}+func Discover(ctx context.Context, rawEndpoint string, allowedHosts, protocolVersions []string, headers http.Header) ([]Tool, string, error) {endpoint, err := ValidatePublicHTTPSEndpoint(ctx, rawEndpoint, allowedHosts, nil)if err != nil {@@ -161,10 +192,14 @@ func Discover(ctx context.Context, rawEndpoint string, allowedHosts, protocolVer}client := NewSecureHTTPClient(endpoint)sessionID := ""- protocolVersion := "2025-03-26"- if len(protocolVersions) > 0 {- protocolVersion = protocolVersions[0]- }+ // An empty list means "whatever this build supports", not "nothing is+ // acceptable". The response is checked against this same slice further+ // down, so leaving it empty rejected every server that answered correctly —+ // which is exactly what it did to the first plugin that used this path.+ if len(protocolVersions) == 0 {+ protocolVersions = SupportedProtocolVersions()+ }+ protocolVersion := protocolVersions[0]initialize := map[string]any{"jsonrpc": "2.0", "id": 1, "method": "initialize","params": map[string]any{diff --git a/server/pkg/remotemcp/devorigin.go b/server/pkg/remotemcp/devorigin.gonew file mode 100644index 0000000000..cbe43b2cd2--- /dev/null+++ b/server/pkg/remotemcp/devorigin.go@@ -0,0 +1,77 @@+package remotemcp++import (+ "crypto/tls"+ "crypto/x509"+ "net/url"+ "os"+ "strings"+)++// The operator opt-in that lets a Plugin author point an `mcp` hook at a server+// running on their own machine.+//+// The `http` transport already has this: MULTICA_PLUGIN_DEV_ORIGINS names exact+// origins whose endpoints skip the public-internet requirement. The `mcp`+// transport did not, so an author had to deploy to the public internet before+// they could try anything — and, for the same reason, the startup path that+// pins approved tools by schema digest could not be exercised by a test at all.+// One asymmetry, both symptoms.+//+// This changes nothing in a deployment that does not set the variable, which is+// every production deployment: with no entries every call below returns false+// and the original checks run unmodified.++// DevOriginsEnv is read by both the server and the daemon. They are separate+// processes, so the value is looked up per call rather than cached at init.+const DevOriginsEnv = "MULTICA_PLUGIN_DEV_ORIGINS"++// DevCAEnv is the CA bundle to trust for those origins. A locally-run MCP+// server still has to speak HTTPS — the manifest validator requires it, and+// relaxing that would mean the URL an administrator consented to no longer says+// whether the connection is encrypted. So the dev allowance is "trust this+// extra CA", never "skip verification".+const DevCAEnv = "MULTICA_PLUGIN_DEV_CA"++// isDevOrigin reports whether the operator named this exact origin.+//+// Exact match on scheme + host + port. A prefix or suffix match would let+// "http://127.0.0.1:9000" authorise "http://127.0.0.1:9000.example.com".+// devTLSConfig returns the TLS config for a dev origin, or nil to leave the+// transport's default alone.+//+// Nil is also what an unreadable or empty CA file yields: failing closed here+// means a mistyped path produces a certificate error, not a silently+// unverified connection.+func devTLSConfig() *tls.Config {+ path := strings.TrimSpace(os.Getenv(DevCAEnv))+ if path == "" {+ return nil+ }+ pem, err := os.ReadFile(path)+ if err != nil {+ return nil+ }+ pool := x509.NewCertPool()+ if !pool.AppendCertsFromPEM(pem) {+ return nil+ }+ return &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12}+}++func isDevOrigin(endpoint *url.URL) bool {+ if endpoint == nil || endpoint.Host == "" {+ return false+ }+ configured := strings.TrimSpace(os.Getenv(DevOriginsEnv))+ if configured == "" {+ return false+ }+ origin := endpoint.Scheme + "://" + endpoint.Host+ for _, entry := range strings.Split(configured, ",") {+ if strings.TrimSpace(entry) == origin {+ return true+ }+ }+ return false+}diff --git a/server/pkg/remotemcp/types.go b/server/pkg/remotemcp/types.goindex e36fa428a3..3c30cda780 100644--- a/server/pkg/remotemcp/types.go+++ b/server/pkg/remotemcp/types.go@@ -37,6 +37,17 @@ type Connection struct {FailurePolicy string `json:"failure_policy"`}+// PluginContributionPrefix marks a connection contributed by an installed+// Plugin rather than by a workspace's own Remote MCP configuration.+//+// The two kinds share one Connection shape and one broker, but their+// credentials live in different places and are served by different routes. The+// daemon holds only the contribution id at dial time, so the id is what has to+// say which kind it is — inferring it from the string's shape would make a+// cloud-issued id that happened to contain a colon resolve against the plugin+// route.+const PluginContributionPrefix = "plugin:"+// DigestBytes is the content digest used to pin approved tool schemas.func DigestBytes(content []byte) string {digest := sha256.Sum256(content)