Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

[MUL-6139] Expand Plugin skills and hosted MCP connections (#6920)

Jiayuan Zhang4d495056e8ac
diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdx
index d7ed3bca66..b2da2233a8 100644
--- a/apps/docs/content/docs/cli.mdx
+++ b/apps/docs/content/docs/cli.mdx
@@ -82,19 +82,6 @@ multica workspace member invite [email protected]
multica workspace member invite [email protected] --role admin
```
-## Private Plugin development
-
-```bash
-multica plugin init ./my-plugin
-multica plugin validate ./my-plugin
-multica plugin pack ./my-plugin --output ./my-plugin.zip
-multica plugin install ./my-plugin.zip --workspace <workspace>
-multica plugin list --workspace <workspace>
-multica plugin status [installation-id|plugin-key] --workspace <workspace>
-```
-
-Private acquisition requires workspace `owner` or `admin` access and both Plugin feature flags. See [Private Skill Plugins](/docs/developers/private-plugins) for the manifest contract, trust model, immutable versions, scope management, and current limits.
-
## Common issue operations
```bash
diff --git a/apps/docs/content/docs/developers/meta.json b/apps/docs/content/docs/developers/meta.json
index c197f429b3..a3ecbd2741 100644
--- a/apps/docs/content/docs/developers/meta.json
+++ b/apps/docs/content/docs/developers/meta.json
@@ -1,4 +1,4 @@
{
"title": "Developers",
- "pages": ["contributing", "architecture", "conventions", "private-plugins"]
+ "pages": ["contributing", "architecture", "conventions"]
}
diff --git a/apps/docs/content/docs/developers/private-plugins.mdx b/apps/docs/content/docs/developers/private-plugins.mdx
deleted file mode 100644
index c8d021c065..0000000000
--- a/apps/docs/content/docs/developers/private-plugins.mdx
+++ /dev/null
@@ -1,83 +0,0 @@
----
-title: Private Skill Plugins
-description: Build, validate, install, upgrade, roll back, and remove workspace-private Agent capabilities.
----
-
-Private Skill Plugins let a workspace add declarative Agent guidance without publishing a new Multica release. V1 accepts static UTF-8 text for `agent.skill.v1`; it is not an npm, Node, Python, WASM, or native extension system, and Multica never runs package-manager or installation hooks from a Plugin.
-
-The feature is intended for internal and self-hosted dogfood. Both `plugins_v1` and `private_plugins_v1` must be enabled to discover, upload, enable, upgrade, or roll back Private Plugins. If `private_plugins_v1` is turned off after installation, existing Private Plugins remain visible in the generic Installed list so administrators can disable or uninstall them safely. Already pinned Runs remain reproducible. Turning off the base `plugins_v1` flag disables all Plugin management APIs.
-
-## Create a Plugin
-
-```bash
-multica plugin init ./my-plugin \
- --key dev.example.release-notes \
- --name "Release Notes" \
- --publisher example.internal
-```
-
-The generated directory has one strict manifest and one Skill:
-
-```text
-my-plugin/
-├── multica.plugin.json
-└── skills/
- └── example-skill/
- └── SKILL.md
-```
-
-`multica.plugin.json` uses `api_version: multica.plugin/v1`, `kind: Plugin`, a reverse-DNS `metadata.key`, semantic `metadata.version`, the V1 daemon features, and only the `agent.skill.contribute` requested capability. Unknown fields or capabilities are rejected. Each contribution entry must be `skills/<contribution-key>/SKILL.md`.
-
-See `examples/plugins/incident-triage` for a complete reference that is deliberately not part of the production bundled catalog.
-
-## Validate and pack
-
-```bash
-multica plugin validate ./my-plugin
-multica plugin pack ./my-plugin --output ./my-plugin-0.1.0.zip
-multica plugin validate ./my-plugin-0.1.0.zip
-```
-
-Packing is deterministic: stable input bytes produce the same ordered ZIP and the same manifest, archive, and artifact digests. Validation rejects unsafe paths, duplicate or case-colliding paths, symlinks, executable files, binary text, undeclared contribution paths, package manifests and install/build hooks, oversized files, and package limits. The Server repeats the complete validation after upload; CLI success is never trusted as authorization or integrity evidence.
-
-## Install or update
-
-Authenticate as a workspace `owner` or `admin`, then run:
-
-```bash
-multica plugin install ./my-plugin --workspace acme
-multica plugin list --workspace acme
-multica plugin status dev.example.release-notes --workspace acme
-```
-
-Only archive bytes are uploaded. The Server does not fetch Git or HTTP URLs, and the stored `source_ref` is derived from the archive digest, so local usernames and absolute paths are not retained.
-
-The first install creates a disabled Installation. Review it in **Settings → Plugins**, where it is labeled **Private / Unverified**, then enable it for the whole workspace or selected Agents. Plugin content does not grant authority by itself: effective access remains the intersection of Kernel Policy, Agent tool permissions, Plugin Grant, Binding, and actor approval.
-
-To publish an update, change `metadata.version` and install again. Releases are immutable:
-
-- Re-uploading the same key, version, and content is idempotent.
-- Reusing a key and version with different content returns a conflict.
-- A new version creates a new immutable release and moves the Installation to it.
-- Existing tasks and retries keep their pinned Execution Manifest and never drift.
-
-Use Settings to roll back to an earlier stored version. Installing the source again upgrades to the new version without a Server restart or deployment.
-
-## Isolation and lifecycle
-
-Private identity is owned by a workspace. Two workspaces may use the same manifest key and version with different artifacts, but cannot enumerate, install, bind, roll back to, or resolve each other's identities and releases. Official identity remains global and separately keyed; a Private Plugin cannot claim official trust or enter the global catalog.
-
-Disabling a Binding removes the capability from matching new tasks. Uninstalling disables the Installation and removes it from future capability snapshots. Immutable releases and artifacts referenced by historical Runs remain available for replay; physical garbage collection is outside V1.
-
-Workspace quotas currently allow 100 private releases and 256 MiB of validated artifact content. A failed validation, conflict, or quota check is transactional and leaves no partial identity, release, or Installation.
-
-## Troubleshooting
-
-- **Private Plugin management is not enabled**: enable both `plugins_v1` and `private_plugins_v1` in the Server feature-flag configuration.
-- **Package is invalid**: run `multica plugin validate <path>` and fix the first fail-closed diagnostic.
-- **Immutable registry conflict**: bump `metadata.version`; never reuse a version for changed content.
-- **Incompatible release**: keep `host_api` within the V1 host range and require both `execution-manifest-v1` and `agent-skill-v1`.
-- **Installation is healthy but the Skill is absent**: confirm at least one workspace or Agent Binding is enabled and that the new task matches that scope.
-- **Permission denied**: installation, update, rollback, Binding changes, and uninstall require a workspace `owner` or `admin`.
-
-V1 does not include remote MCP, Secrets, network grants, Git/HTTP registries, install hooks, arbitrary executable code, UI contributions, automation contributions, community distribution, publisher verification, billing, or artifact garbage collection.
diff --git a/examples/plugins/exa-search/multica.plugin.json b/examples/plugins/exa-search/multica.plugin.json
new file mode 100644
index 0000000000..20f731a59c
--- /dev/null
+++ b/examples/plugins/exa-search/multica.plugin.json
@@ -0,0 +1,66 @@
+{
+ "api_version": "multica.plugin/v1",
+ "kind": "Plugin",
+ "metadata": {
+ "key": "dev.multica.exa-search",
+ "name": "Exa Search",
+ "description": "Reference Exa Plugin with research guidance and hosted web search tools",
+ "version": "0.3.0",
+ "publisher": "multica.examples"
+ },
+ "compatibility": {
+ "host_api": ">=1.0.0 <2.0.0",
+ "required_daemon_features": [
+ "execution-manifest-v1",
+ "agent-skill-v1",
+ "remote-mcp-v1"
+ ]
+ },
+ "requested_capabilities": [
+ "agent.skill.contribute",
+ "tool.remote-mcp.connect"
+ ],
+ "contributes": {
+ "agent_skills": [
+ {
+ "key": "exa-research",
+ "name": "Exa Research Guidance",
+ "description": "Use Exa for current web research, deep dives, competitive analysis, lead discovery, and source-backed investigation.",
+ "entry": "skills/exa-research/SKILL.md"
+ }
+ ],
+ "remote_mcp": [
+ {
+ "key": "exa-search",
+ "name": "Exa Search",
+ "description": "Search the public web and fetch page content through Exa's hosted MCP server",
+ "transport": "streamable-http",
+ "protocol_versions": ["2025-03-26", "2024-11-05"],
+ "endpoint_policy": {
+ "default_endpoint": "https://mcp.exa.ai/mcp",
+ "allowed_hosts": ["mcp.exa.ai"]
+ },
+ "authentication": {
+ "preferred": "none",
+ "supported": ["none", "bearer"]
+ },
+ "tool_intent": [
+ {
+ "name": "web_search_exa",
+ "description": "Search the web for a topic and return relevant content",
+ "risk": "read"
+ },
+ {
+ "name": "web_fetch_exa",
+ "description": "Fetch webpage content as clean markdown",
+ "risk": "read"
+ }
+ ],
+ "configuration_schema": {
+ "type": "object",
+ "additionalProperties": false
+ }
+ }
+ ]
+ }
+}
diff --git a/examples/plugins/exa-search/skills/exa-research/SKILL.md b/examples/plugins/exa-search/skills/exa-research/SKILL.md
new file mode 100644
index 0000000000..551994c180
--- /dev/null
+++ b/examples/plugins/exa-search/skills/exa-research/SKILL.md
@@ -0,0 +1,25 @@
+---
+name: exa-research
+description: "Use Exa for current web research, deep dives, competitive analysis, lead discovery, literature reviews, and source-backed investigation. Trigger on requests to research, search the web, find current information, compare competitors, discover companies or people, or investigate a topic across multiple sources."
+---
+
+# Exa research
+
+Use the approved Exa MCP tools for web research in this workspace.
+
+## Tool choice
+
+- Start with `web_search_exa` when the user needs current facts, sources, companies, people, news, comparisons, or broader discovery.
+- Use a semantically rich query that describes the ideal result, not a short keyword list.
+- Use `web_fetch_exa` after search when snippets are insufficient, or when the user gives one or more URLs whose full contents must be read.
+- Batch URLs into one `web_fetch_exa` call when possible.
+
+## Workflow
+
+1. Clarify the target, time range, filters, and desired output when they materially change the search.
+2. Search broadly enough for the requested depth, then discard results that do not meet the user's criteria.
+3. Fetch the strongest sources when their full context is needed.
+4. Deduplicate repeated URLs and cross-check important claims across independent sources.
+5. Answer with linked sources and distinguish sourced facts from inference.
+
+If Exa is unavailable or rate-limited, report the exact failure and the authentication or configuration needed. Do not silently substitute a different search provider when the request or task specifically requires Exa.
diff --git a/examples/plugins/incident-triage/skills/incident-triage/references/severity-guide.md b/examples/plugins/incident-triage/skills/incident-triage/references/severity-guide.md
new file mode 100644
index 0000000000..ec2ebdffd1
--- /dev/null
+++ b/examples/plugins/incident-triage/skills/incident-triage/references/severity-guide.md
@@ -0,0 +1,5 @@
+# Severity guide
+
+- SEV-1: Widespread critical impact with no workaround.
+- SEV-2: Significant impact with a partial workaround.
+- SEV-3: Limited impact or a complete workaround.
diff --git a/examples/plugins/mobbin/multica.plugin.json b/examples/plugins/mobbin/multica.plugin.json
new file mode 100644
index 0000000000..be605014ad
--- /dev/null
+++ b/examples/plugins/mobbin/multica.plugin.json
@@ -0,0 +1,61 @@
+{
+ "api_version": "multica.plugin/v1",
+ "kind": "Plugin",
+ "metadata": {
+ "key": "dev.multica.mobbin-design-reference",
+ "name": "Mobbin Design Reference",
+ "description": "Example Plugin combining Mobbin design-research guidance with Mobbin's OAuth-protected hosted MCP server",
+ "version": "0.2.0",
+ "publisher": "multica.examples"
+ },
+ "compatibility": {
+ "host_api": ">=1.0.0 <2.0.0",
+ "required_daemon_features": [
+ "execution-manifest-v1",
+ "agent-skill-v1",
+ "remote-mcp-v1"
+ ]
+ },
+ "requested_capabilities": [
+ "agent.skill.contribute",
+ "tool.remote-mcp.connect"
+ ],
+ "contributes": {
+ "agent_skills": [
+ {
+ "key": "mobbin-design-research",
+ "name": "Mobbin Design Research",
+ "description": "Research real shipped screens and flows before designing or reviewing product interfaces.",
+ "entry": "skills/mobbin-design-research/SKILL.md"
+ }
+ ],
+ "remote_mcp": [
+ {
+ "key": "mobbin",
+ "name": "Mobbin",
+ "description": "Search Mobbin's hosted library of real product screens and flows",
+ "transport": "streamable-http",
+ "protocol_versions": ["2025-03-26", "2024-11-05"],
+ "endpoint_policy": {
+ "default_endpoint": "https://api.mobbin.com/mcp",
+ "allowed_hosts": ["api.mobbin.com"]
+ },
+ "authentication": {
+ "preferred": "oauth",
+ "supported": ["oauth"]
+ },
+ "tool_intent": [
+ {
+ "name": "*",
+ "description": "Discover Mobbin's authenticated research tools for explicit administrator review.",
+ "risk": "write"
+ }
+ ],
+ "configuration_schema": {
+ "type": "object",
+ "additionalProperties": false
+ }
+ }
+ ]
+ }
+}
diff --git a/examples/plugins/mobbin/skills/mobbin-design-research/SKILL.md b/examples/plugins/mobbin/skills/mobbin-design-research/SKILL.md
new file mode 100644
index 0000000000..5a37b5dbc0
--- /dev/null
+++ b/examples/plugins/mobbin/skills/mobbin-design-research/SKILL.md
@@ -0,0 +1,23 @@
+---
+name: mobbin-design-research
+description: Use Mobbin's approved MCP tools to research real shipped product screens and flows before designing or reviewing interfaces. Trigger for UI/UX pattern research, competitive design comparisons, onboarding, checkout, paywall, permissions, navigation, empty states, error states, and other requests that benefit from concrete app references.
+---
+
+# Mobbin Design Research
+
+Use the Mobbin MCP tools to ground design decisions in real product examples. Treat the returned screens as research inputs, not templates to copy blindly.
+
+## Workflow
+
+1. Translate the request into a concrete pattern, platform, industry, and user state. Preserve the user's constraints and style guide.
+2. Search broadly enough to compare several relevant shipped products. Refine the query when results mix unrelated flows.
+3. Inspect the strongest examples and identify repeated patterns, meaningful differences, and likely tradeoffs.
+4. Synthesize the evidence into recommendations for the user's product. Explain why a pattern fits the current context instead of merely listing screenshots.
+5. Attribute examples to the product and platform shown by Mobbin, and distinguish observed details from your inference.
+
+## Guardrails
+
+- Prefer recent and contextually similar examples, but include a contrasting approach when it clarifies the decision.
+- Do not imply that popularity proves usability or that a visual pattern is universally correct.
+- Do not reproduce a product's branded screen verbatim. Adapt structure and interaction principles to the user's own system.
+- If Mobbin is unavailable or requires authorization, report that directly and state what research could not be completed.
diff --git a/examples/plugins/mobbin/skills/mobbin-design-research/agents/openai.yaml b/examples/plugins/mobbin/skills/mobbin-design-research/agents/openai.yaml
new file mode 100644
index 0000000000..193b0de448
--- /dev/null
+++ b/examples/plugins/mobbin/skills/mobbin-design-research/agents/openai.yaml
@@ -0,0 +1,4 @@
+interface:
+ display_name: "Mobbin Design Research"
+ short_description: "Research proven UI patterns with Mobbin"
+ default_prompt: "Use $mobbin-design-research to research proven product patterns for this interface."
diff --git a/examples/plugins/remote-mcp-fixture/multica.plugin.json b/examples/plugins/remote-mcp-fixture/multica.plugin.json
new file mode 100644
index 0000000000..70febc6965
--- /dev/null
+++ b/examples/plugins/remote-mcp-fixture/multica.plugin.json
@@ -0,0 +1,51 @@
+{
+ "api_version": "multica.plugin/v1",
+ "kind": "Plugin",
+ "metadata": {
+ "key": "dev.multica.remote-mcp-fixture",
+ "name": "Remote MCP Fixture",
+ "description": "Reference Remote MCP Plugin with deterministic read and write tools",
+ "version": "1.0.0",
+ "publisher": "multica.dev"
+ },
+ "compatibility": {
+ "host_api": ">=1.0.0 <2.0.0",
+ "required_daemon_features": [
+ "execution-manifest-v1",
+ "remote-mcp-v1"
+ ]
+ },
+ "requested_capabilities": [
+ "tool.remote-mcp.connect"
+ ],
+ "contributes": {
+ "remote_mcp": [
+ {
+ "key": "fixture-tools",
+ "name": "Fixture Tools",
+ "description": "Exercises Remote MCP discovery, approval, read, and write paths",
+ "transport": "streamable-http",
+ "protocol_versions": ["2025-03-26"],
+ "endpoint_policy": {
+ "allowed_hosts": ["mcp-fixture.example.com"]
+ },
+ "tool_intent": [
+ {
+ "name": "fixture.read",
+ "description": "Read a deterministic fixture value",
+ "risk": "read"
+ },
+ {
+ "name": "fixture.write",
+ "description": "Append a value to the fixture log",
+ "risk": "write"
+ }
+ ],
+ "configuration_schema": {
+ "type": "object",
+ "additionalProperties": false
+ }
+ }
+ ]
+ }
+}
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 60c9fe2381..3e8a4a4834 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -69,6 +69,27 @@ describe("ApiClient pull-request response schema", () => {
});
});
+describe("ApiClient Remote MCP OAuth response schema", () => {
+ it("degrades a malformed start response without inventing a navigation URL", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ authorization_url: 42 }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ ),
+ );
+
+ await expect(new ApiClient("https://api.example.test").startPluginRemoteMCPOAuth(
+ "workspace-1",
+ "installation-1",
+ "search",
+ { public_config: {}, failure_policy: "required" },
+ )).resolves.toEqual({ authorization_url: "" });
+ });
+});
+
describe("ApiClient server Table query", () => {
it("posts the canonical query to the group and branch endpoints", async () => {
const fetchMock = vi
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 746106d999..a085039746 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -145,6 +145,10 @@ import type {
PluginInstallation,
PluginInstallationListResponse,
PluginReleaseRequest,
+ RemoteMCPConfigRequest,
+ RemoteMCPDiscoveryResponse,
+ RemoteMCPOAuthStartRequest,
+ RemoteMCPOAuthStartResponse,
GitHubPullRequest,
ListGitHubInstallationsResponse,
ListGitHubRepositoriesResponse,
@@ -377,6 +381,9 @@ import {
PluginCatalogResponseSchema,
PluginInstallationListResponseSchema,
PluginInstallationSchema,
+ RemoteMCPDiscoveryResponseSchema,
+ RemoteMCPOAuthStartResponseSchema,
+ EMPTY_REMOTE_MCP_OAUTH_START_RESPONSE,
WorkspaceMcpServerListSchema,
WorkspaceMcpServerSchema,
type IssueView,
@@ -2444,6 +2451,49 @@ export class ApiClient {
});
}
+ async configurePluginRemoteMCP(workspaceId: string, installationId: string, contributionKey: string, request: RemoteMCPConfigRequest): Promise<RemoteMCPDiscoveryResponse> {
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/remote-mcp/${encodeURIComponent(contributionKey)}/config`, {
+ method: "PUT",
+ body: JSON.stringify(request),
+ });
+ return parseWithFallback(raw, RemoteMCPDiscoveryResponseSchema, { config_revision: 0, discovered_tools: [], discovered_schema_digest: "" }, {
+ endpoint: "PUT /api/workspaces/{id}/plugins/{installationId}/remote-mcp/{contributionKey}/config",
+ });
+ }
+
+ async testPluginRemoteMCP(workspaceId: string, installationId: string, contributionKey: string): Promise<RemoteMCPDiscoveryResponse> {
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/remote-mcp/${encodeURIComponent(contributionKey)}/test`, {
+ method: "POST",
+ body: JSON.stringify({}),
+ });
+ return parseWithFallback(raw, RemoteMCPDiscoveryResponseSchema, { config_revision: 0, discovered_tools: [], discovered_schema_digest: "" }, {
+ endpoint: "POST /api/workspaces/{id}/plugins/{installationId}/remote-mcp/{contributionKey}/test",
+ });
+ }
+
+ async startPluginRemoteMCPOAuth(workspaceId: string, installationId: string, contributionKey: string, request: RemoteMCPOAuthStartRequest): Promise<RemoteMCPOAuthStartResponse> {
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/remote-mcp/${encodeURIComponent(contributionKey)}/oauth/start`, {
+ method: "POST",
+ body: JSON.stringify(request),
+ });
+ return parseWithFallback(raw, RemoteMCPOAuthStartResponseSchema, EMPTY_REMOTE_MCP_OAUTH_START_RESPONSE, {
+ endpoint: "POST /api/workspaces/{id}/plugins/{installationId}/remote-mcp/{contributionKey}/oauth/start",
+ });
+ }
+
+ async approvePluginRemoteMCPTools(workspaceId: string, installationId: string, contributionKey: string, tools: string[]): Promise<void> {
+ await this.fetch(`/api/workspaces/${workspaceId}/plugins/${installationId}/remote-mcp/${encodeURIComponent(contributionKey)}/approve`, {
+ method: "POST",
+ body: JSON.stringify({ tools }),
+ });
+ }
+
+ async revokePluginRemoteMCPCredential(workspaceId: string, installationId: string, contributionKey: string): Promise<void> {
+ await this.fetch(`/api/workspaces/${workspaceId}/plugins/${installationId}/remote-mcp/${encodeURIComponent(contributionKey)}/credential`, {
+ method: "DELETE",
+ });
+ }
+
// Members
async listMembers(workspaceId: string): Promise<MemberWithUser[]> {
return this.fetch(`/api/workspaces/${workspaceId}/members`);
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 72aed3c4a8..311bb4cc96 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -50,6 +50,9 @@ import {
EMPTY_PLUGIN_CATALOG,
PluginCatalogResponseSchema,
PluginInstallationSchema,
+ RemoteMCPDiscoveryResponseSchema,
+ RemoteMCPOAuthStartResponseSchema,
+ EMPTY_REMOTE_MCP_OAUTH_START_RESPONSE,
} from "./schemas";
import { IssueViewSchema, IssueViewListSchema } from "./schemas";
import { parseWithFallback } from "./schema";
@@ -1386,6 +1389,54 @@ describe("Plugin catalog schemas", () => {
expect(parsed.trust_tier).toBe("");
expect(parsed.signature_verified).toBe(false);
expect(parsed.contribution_details).toEqual([]);
+ expect(parsed.remote_mcp).toEqual([]);
+ });
+
+ it("parses Remote MCP status without accepting secret-shaped response fields", () => {
+ const parsed = PluginInstallationSchema.parse({
+ id: "installation-1",
+ remote_mcp: [{
+ contribution_key: "search",
+ credential_state: "configured",
+ credential_hint: "••••1234",
+ credential: "must-not-be-modeled",
+ approved_tools: [{
+ name: "search.read",
+ input_schema: { type: "object" },
+ schema_digest: "sha256:fixture",
+ risk: "read",
+ }],
+ reviewed: true,
+ ready: true,
+ }],
+ });
+ expect(parsed.remote_mcp[0]?.credential_state).toBe("configured");
+ expect(parsed.remote_mcp[0]?.approved_tools[0]?.name).toBe("search.read");
+ expect(parsed.remote_mcp[0]?.ready).toBe(true);
+ expect(parsed.remote_mcp[0]).not.toHaveProperty("credential");
+ });
+
+ it("defaults a malformed Remote MCP discovery response without inventing tools", () => {
+ const fallback = { config_revision: 0, discovered_tools: [], discovered_schema_digest: "" };
+ const parsed = parseWithFallback(
+ { config_revision: "bad", discovered_tools: { name: "search" } },
+ RemoteMCPDiscoveryResponseSchema,
+ fallback,
+ { endpoint: "POST /api/workspaces/{id}/plugins/{installationId}/remote-mcp/{key}/test" },
+ );
+ expect(parsed).toEqual(fallback);
+ });
+
+ it("rejects a malformed Remote MCP OAuth start response", () => {
+ expect(parseWithFallback(
+ { authorization_url: undefined },
+ RemoteMCPOAuthStartResponseSchema,
+ EMPTY_REMOTE_MCP_OAUTH_START_RESPONSE,
+ { endpoint: "POST /api/workspaces/{id}/plugins/{installationId}/remote-mcp/{key}/oauth/start" },
+ )).toEqual(EMPTY_REMOTE_MCP_OAUTH_START_RESPONSE);
+ expect(RemoteMCPOAuthStartResponseSchema.parse({
+ authorization_url: "https://auth.example.test/authorize?state=opaque",
+ }).authorization_url).toContain("auth.example.test");
});
it("degrades a malformed catalog response to unsupported and empty", () => {
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index a977920b96..74b42112df 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -82,6 +82,53 @@ export const PluginBindingSchema = z.object({
revision: z.number().default(0),
}).loose();
+export const RemoteMCPToolSchema = z.object({
+ name: z.string(),
+ description: z.string().optional(),
+ input_schema: z.record(z.string(), z.unknown()).default({}),
+ schema_digest: z.string().default(""),
+ risk: z.string().optional(),
+});
+
+export const PluginRemoteMCPConfigSchema = z.object({
+ contribution_key: z.string(),
+ default_endpoint: z.string().optional(),
+ preferred_auth: z.string().optional(),
+ supported_auth: z.array(z.string()).default([]),
+ config_revision: z.number().optional(),
+ endpoint: z.string().optional(),
+ endpoint_domain: z.string().optional(),
+ auth_type: z.string().optional(),
+ auth_header: z.string().optional(),
+ public_config: z.record(z.string(), z.unknown()).optional(),
+ connection_scope: z.string().optional(),
+ connected_by: z.string().optional(),
+ credential_state: z.string().default("missing"),
+ credential_hint: z.string().optional(),
+ failure_policy: z.string().optional(),
+ approved_tools: z.array(RemoteMCPToolSchema).default([]),
+ discovered_tools: z.array(RemoteMCPToolSchema).default([]),
+ discovered_schema_digest: z.string().optional(),
+ schema_digest: z.string().optional(),
+ reviewed: z.boolean().default(false),
+ ready: z.boolean().default(false),
+});
+
+export const RemoteMCPDiscoveryResponseSchema = z.object({
+ ok: z.boolean().optional(),
+ config_revision: z.number().default(0),
+ credential_state: z.string().optional(),
+ reviewed: z.boolean().optional(),
+ discovered_tools: z.array(RemoteMCPToolSchema).default([]),
+ discovered_schema_digest: z.string().default(""),
+});
+
+export const RemoteMCPOAuthStartResponseSchema = z.object({
+ authorization_url: z.string().url(),
+});
+
+export const EMPTY_REMOTE_MCP_OAUTH_START_RESPONSE = { authorization_url: "" };
+
export const PluginInstallationSchema = z.object({
id: z.string(),
plugin_key: z.string().default(""),
@@ -117,6 +164,7 @@ export const PluginInstallationSchema = z.object({
entry_digest: z.string().default(""),
}).loose()).default([]),
bindings: z.array(PluginBindingSchema).default([]),
+ remote_mcp: z.array(PluginRemoteMCPConfigSchema).default([]),
}).loose();
export const EMPTY_PLUGIN_INSTALLATION: PluginInstallation = {
@@ -142,6 +190,7 @@ export const EMPTY_PLUGIN_INSTALLATION: PluginInstallation = {
contributions: [],
contribution_details: [],
bindings: [],
+ remote_mcp: [],
};
export const PluginInstallationListResponseSchema = z.object({
diff --git a/packages/core/feature-flags/index.ts b/packages/core/feature-flags/index.ts
index aa53378a6a..4683dcb667 100644
--- a/packages/core/feature-flags/index.ts
+++ b/packages/core/feature-flags/index.ts
@@ -21,7 +21,6 @@ export {
BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,
COMPOSIO_MCP_APPS_FLAG,
PLUGINS_V1_FLAG,
- PRIVATE_PLUGINS_V1_FLAG,
} from "./keys";
export {
FeatureFlagsProvider,
diff --git a/packages/core/feature-flags/keys.ts b/packages/core/feature-flags/keys.ts
index 3648f9d232..db0dd7123d 100644
--- a/packages/core/feature-flags/keys.ts
+++ b/packages/core/feature-flags/keys.ts
@@ -2,4 +2,3 @@ export const COMPOSIO_MCP_APPS_FLAG = "composio_mcp_apps";
export const PLUGINS_V1_FLAG = "plugins_v1";
export const BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG =
"billing_workspace_subscriptions";
-export const PRIVATE_PLUGINS_V1_FLAG = "private_plugins_v1";
diff --git a/packages/core/plugins/mutations.ts b/packages/core/plugins/mutations.ts
index e24facc7b6..e98c3c5c31 100644
--- a/packages/core/plugins/mutations.ts
+++ b/packages/core/plugins/mutations.ts
@@ -1,6 +1,6 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "../api";
-import type { PluginBindingRequest, PluginReleaseRequest } from "../types";
+import type { PluginBindingRequest, PluginReleaseRequest, RemoteMCPConfigRequest, RemoteMCPOAuthStartRequest } from "../types";
import { pluginKeys } from "./queries";
function useInvalidatePlugins(wsId: string) {
@@ -53,3 +53,44 @@ export function useUninstallPlugin(wsId: string) {
onSettled: invalidate,
});
}
+
+export function useConfigurePluginRemoteMCP(wsId: string) {
+ const invalidate = useInvalidatePlugins(wsId);
+ return useMutation({
+ mutationFn: ({ installationId, contributionKey, request }: { installationId: string; contributionKey: string; request: RemoteMCPConfigRequest }) =>
+ api.configurePluginRemoteMCP(wsId, installationId, contributionKey, request),
+ onSettled: invalidate,
+ });
+}
+
+export function useTestPluginRemoteMCP(wsId: string) {
+ return useMutation({
+ mutationFn: ({ installationId, contributionKey }: { installationId: string; contributionKey: string }) =>
+ api.testPluginRemoteMCP(wsId, installationId, contributionKey),
+ });
+}
+
+export function useStartPluginRemoteMCPOAuth(wsId: string) {
+ return useMutation({
+ mutationFn: ({ installationId, contributionKey, request }: { installationId: string; contributionKey: string; request: RemoteMCPOAuthStartRequest }) =>
+ api.startPluginRemoteMCPOAuth(wsId, installationId, contributionKey, request),
+ });
+}
+
+export function useApprovePluginRemoteMCPTools(wsId: string) {
+ const invalidate = useInvalidatePlugins(wsId);
+ return useMutation({
+ mutationFn: ({ installationId, contributionKey, tools }: { installationId: string; contributionKey: string; tools: string[] }) =>
+ api.approvePluginRemoteMCPTools(wsId, installationId, contributionKey, tools),
+ onSettled: invalidate,
+ });
+}
+
+export function useRevokePluginRemoteMCPCredential(wsId: string) {
+ const invalidate = useInvalidatePlugins(wsId);
+ return useMutation({
+ mutationFn: ({ installationId, contributionKey }: { installationId: string; contributionKey: string }) =>
+ api.revokePluginRemoteMCPCredential(wsId, installationId, contributionKey),
+ onSettled: invalidate,
+ });
+}
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 851e925fa3..b5e539dbe1 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -87,6 +87,12 @@ export type {
PluginInstallationListResponse,
PluginReleaseRequest,
PluginBindingRequest,
+ PluginRemoteMCPConfig,
+ RemoteMCPConfigRequest,
+ RemoteMCPDiscoveryResponse,
+ RemoteMCPOAuthStartRequest,
+ RemoteMCPOAuthStartResponse,
+ RemoteMCPTool,
} from "./plugin";
export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread } from "./inbox";
export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } from "./notification-preference";
diff --git a/packages/core/types/plugin.ts b/packages/core/types/plugin.ts
index 6d03d5cf34..e25a9e7d01 100644
--- a/packages/core/types/plugin.ts
+++ b/packages/core/types/plugin.ts
@@ -33,6 +33,74 @@ export interface PluginInstallation {
contributions: string[];
contribution_details: PluginCatalogContribution[];
bindings: PluginBinding[];
+ remote_mcp: PluginRemoteMCPConfig[];
+}
+
+export interface RemoteMCPTool {
+ name: string;
+ description?: string;
+ input_schema: Record<string, unknown>;
+ schema_digest: string;
+ risk?: "read" | "write" | string;
+}
+
+export interface PluginRemoteMCPConfig {
+ contribution_key: string;
+ default_endpoint?: string;
+ preferred_auth?: "none" | "oauth" | "bearer" | "header" | string;
+ supported_auth?: string[];
+ config_revision?: number;
+ endpoint?: string;
+ endpoint_domain?: string;
+ auth_type?: "none" | "oauth" | "bearer" | "header" | string;
+ auth_header?: string;
+ public_config?: Record<string, unknown>;
+ connection_scope?: "workspace" | "user" | string;
+ connected_by?: string;
+ credential_state: "missing" | "configured" | "revoked" | "not_required" | string;
+ credential_hint?: string;
+ failure_policy?: "required" | "optional" | string;
+ approved_tools: RemoteMCPTool[];
+ discovered_tools: RemoteMCPTool[];
+ discovered_schema_digest?: string;
+ schema_digest?: string;
+ reviewed: boolean;
+ ready: boolean;
+}
+
+export interface RemoteMCPConfigRequest {
+ endpoint: string;
+ public_config: Record<string, unknown>;
+ auth_type: "none" | "bearer" | "header";
+ auth_header?: string;
+ credential?: string;
+ failure_policy: "required" | "optional";
+}
+
+export interface RemoteMCPDiscoveryResponse {
+ ok?: boolean;
+ config_revision: number;
+ credential_state?: string;
+ reviewed?: boolean;
+ discovered_tools: RemoteMCPTool[];
+ discovered_schema_digest: string;
+}
+
+export interface RemoteMCPOAuthStartRequest {
+ endpoint?: string;
+ public_config: Record<string, unknown>;
+ failure_policy: "required" | "optional";
+ scope?: string;
+ client_id?: string;
+ client_secret?: string;
+ token_endpoint_auth_method?: "none" | "client_secret_basic" | "client_secret_post";
+ authorization_endpoint?: string;
+ token_endpoint?: string;
+ return_to?: string;
+}
+
+export interface RemoteMCPOAuthStartResponse {
+ authorization_url: string;
}
export interface PluginCatalogContribution {
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 36e2b0fbb3..a365004d81 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -273,6 +273,66 @@
"host_api": "Host API",
"publisher": "Publisher and signing identity",
"none": "None"
+ },
+ "remote_mcp": {
+ "title": "Remote MCP connection",
+ "endpoint": "HTTPS endpoint",
+ "endpoint_placeholder": "https://mcp.example.com/mcp",
+ "auth": "Authentication",
+ "auth_types": {
+ "none": "None",
+ "oauth": "OAuth (recommended)",
+ "bearer": "Bearer token",
+ "header": "Custom header"
+ },
+ "header_name": "Header name",
+ "credential": "Credential (stored encrypted)",
+ "connect": "Connect",
+ "connected": "Connected",
+ "ready_to_connect": "Ready to connect",
+ "complete_before_enabling": "Connect the MCP and approve at least one tool before enabling a scope.",
+ "advanced": "Advanced configuration",
+ "oauth_scope": "OAuth scopes (automatic when empty)",
+ "oauth_client_id": "OAuth client ID (automatic when empty)",
+ "oauth_client_secret": "OAuth client secret",
+ "oauth_authorization_endpoint": "Authorization endpoint override",
+ "oauth_token_endpoint": "Token endpoint override",
+ "oauth_token_auth_method": "Token endpoint authentication",
+ "oauth_token_auth_methods": {
+ "none": "Public client (PKCE)",
+ "client_secret_basic": "Client secret (HTTP Basic)",
+ "client_secret_post": "Client secret (request body)"
+ },
+ "public_config": "Public configuration (JSON object)",
+ "invalid_public_config": "Public configuration must be a valid JSON object",
+ "failure_policy": "Failure policy",
+ "failure_policies": {
+ "required": "Required — stop the task",
+ "optional": "Optional — continue without tools"
+ },
+ "configure_and_discover": "Save and discover tools",
+ "test": "Test connection",
+ "approve": "Approve selected tools",
+ "revoke": "Revoke credential",
+ "credential_states": {
+ "configured": "Credential configured",
+ "revoked": "Credential revoked",
+ "missing": "Credential missing",
+ "not_required": "No credential required"
+ },
+ "reviewed": "Tools approved",
+ "pending_review": "Approval required",
+ "approved_tools": "Approved tools",
+ "no_tools": "The server did not advertise any tools.",
+ "discovery": "Discovered tools — review access explicitly",
+ "read": "Read",
+ "write": "Write",
+ "configured_success": "Connection saved; review the discovered tools",
+ "oauth_connected_success": "OAuth connection completed; review the discovered tools",
+ "oauth_connect_failed": "OAuth connection could not be completed. Try again.",
+ "test_success": "Connection test succeeded",
+ "approved_success": "Tool access approved",
+ "revoked_success": "Credential revoked and the Plugin disabled"
}
},
"properties": {
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 595bff5b96..d3ee3c5eef 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -273,6 +273,66 @@
"host_api": "Host API",
"publisher": "発行元と署名 ID",
"none": "なし"
+ },
+ "remote_mcp": {
+ "title": "Remote MCP 接続",
+ "endpoint": "HTTPS エンドポイント",
+ "endpoint_placeholder": "https://mcp.example.com/mcp",
+ "auth": "認証",
+ "auth_types": {
+ "none": "なし",
+ "oauth": "OAuth(推奨)",
+ "bearer": "Bearer トークン",
+ "header": "カスタムヘッダー"
+ },
+ "header_name": "ヘッダー名",
+ "credential": "認証情報(暗号化して保存)",
+ "connect": "接続",
+ "connected": "接続済み",
+ "ready_to_connect": "接続できます",
+ "complete_before_enabling": "スコープを有効にする前に MCP に接続し、少なくとも 1 つのツールを承認してください。",
+ "advanced": "詳細設定",
+ "oauth_scope": "OAuth スコープ(空欄は自動)",
+ "oauth_client_id": "OAuth クライアント ID(空欄は自動)",
+ "oauth_client_secret": "OAuth クライアントシークレット",
+ "oauth_authorization_endpoint": "認可エンドポイントの上書き",
+ "oauth_token_endpoint": "トークンエンドポイントの上書き",
+ "oauth_token_auth_method": "トークンエンドポイント認証",
+ "oauth_token_auth_methods": {
+ "none": "パブリッククライアント(PKCE)",
+ "client_secret_basic": "クライアントシークレット(HTTP Basic)",
+ "client_secret_post": "クライアントシークレット(リクエスト本文)"
+ },
+ "public_config": "公開設定(JSON オブジェクト)",
+ "invalid_public_config": "公開設定には有効な JSON オブジェクトを指定してください",
+ "failure_policy": "障害ポリシー",
+ "failure_policies": {
+ "required": "必須 — タスクを停止",
+ "optional": "任意 — ツールなしで続行"
+ },
+ "configure_and_discover": "保存してツールを検出",
+ "test": "接続をテスト",
+ "approve": "選択したツールを承認",
+ "revoke": "認証情報を失効",
+ "credential_states": {
+ "configured": "認証情報を設定済み",
+ "revoked": "認証情報を失効済み",
+ "missing": "認証情報がありません",
+ "not_required": "認証情報は不要"
+ },
+ "reviewed": "ツールを承認済み",
+ "pending_review": "承認が必要",
+ "approved_tools": "承認済みツール",
+ "no_tools": "サーバーからツールが通知されませんでした。",
+ "discovery": "検出されたツール — アクセスを明示的に確認してください",
+ "read": "読み取り",
+ "write": "書き込み",
+ "configured_success": "接続を保存しました。検出されたツールを確認してください",
+ "oauth_connected_success": "OAuth 接続が完了しました。検出されたツールを確認してください",
+ "oauth_connect_failed": "OAuth 接続を完了できませんでした。もう一度お試しください。",
+ "test_success": "接続テストに成功しました",
+ "approved_success": "ツールへのアクセスを承認しました",
+ "revoked_success": "認証情報を失効し、Plugin を無効にしました"
}
},
"properties": {
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 7eb2db4259..3436bb5918 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -273,6 +273,66 @@
"host_api": "Host API",
"publisher": "게시자 및 서명 ID",
"none": "없음"
+ },
+ "remote_mcp": {
+ "title": "Remote MCP 연결",
+ "endpoint": "HTTPS 엔드포인트",
+ "endpoint_placeholder": "https://mcp.example.com/mcp",
+ "auth": "인증",
+ "auth_types": {
+ "none": "없음",
+ "oauth": "OAuth(권장)",
+ "bearer": "Bearer 토큰",
+ "header": "사용자 지정 헤더"
+ },
+ "header_name": "헤더 이름",
+ "credential": "인증 정보(암호화 저장)",
+ "connect": "연결",
+ "connected": "연결됨",
+ "ready_to_connect": "연결할 수 있음",
+ "complete_before_enabling": "범위를 활성화하기 전에 MCP를 연결하고 도구를 하나 이상 승인하세요.",
+ "advanced": "고급 구성",
+ "oauth_scope": "OAuth 범위(비워두면 자동)",
+ "oauth_client_id": "OAuth 클라이언트 ID(비워두면 자동)",
+ "oauth_client_secret": "OAuth 클라이언트 보안 비밀",
+ "oauth_authorization_endpoint": "인증 엔드포인트 재정의",
+ "oauth_token_endpoint": "토큰 엔드포인트 재정의",
+ "oauth_token_auth_method": "토큰 엔드포인트 인증",
+ "oauth_token_auth_methods": {
+ "none": "공개 클라이언트(PKCE)",
+ "client_secret_basic": "클라이언트 시크릿(HTTP Basic)",
+ "client_secret_post": "클라이언트 시크릿(요청 본문)"
+ },
+ "public_config": "공개 설정(JSON 객체)",
+ "invalid_public_config": "공개 설정은 유효한 JSON 객체여야 합니다",
+ "failure_policy": "실패 정책",
+ "failure_policies": {
+ "required": "필수 — 태스크 중지",
+ "optional": "선택 — 도구 없이 계속"
+ },
+ "configure_and_discover": "저장하고 도구 검색",
+ "test": "연결 테스트",
+ "approve": "선택한 도구 승인",
+ "revoke": "인증 정보 폐기",
+ "credential_states": {
+ "configured": "인증 정보 설정됨",
+ "revoked": "인증 정보 폐기됨",
+ "missing": "인증 정보 없음",
+ "not_required": "인증 정보 필요 없음"
+ },
+ "reviewed": "도구 승인됨",
+ "pending_review": "승인 필요",
+ "approved_tools": "승인된 도구",
+ "no_tools": "서버에서 알린 도구가 없습니다.",
+ "discovery": "검색된 도구 — 접근 권한을 명시적으로 검토하세요",
+ "read": "읽기",
+ "write": "쓰기",
+ "configured_success": "연결을 저장했습니다. 검색된 도구를 검토하세요",
+ "oauth_connected_success": "OAuth 연결이 완료되었습니다. 검색된 도구를 검토하세요",
+ "oauth_connect_failed": "OAuth 연결을 완료하지 못했습니다. 다시 시도하세요.",
+ "test_success": "연결 테스트에 성공했습니다",
+ "approved_success": "도구 접근을 승인했습니다",
+ "revoked_success": "인증 정보를 폐기하고 Plugin을 비활성화했습니다"
}
},
"properties": {
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 86fb02fd04..3dcb726753 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -273,6 +273,66 @@
"host_api": "Host API",
"publisher": "发布者与签名身份",
"none": "无"
+ },
+ "remote_mcp": {
+ "title": "Remote MCP 连接",
+ "endpoint": "HTTPS 端点",
+ "endpoint_placeholder": "https://mcp.example.com/mcp",
+ "auth": "身份验证",
+ "auth_types": {
+ "none": "无",
+ "oauth": "OAuth(推荐)",
+ "bearer": "Bearer 令牌",
+ "header": "自定义请求头"
+ },
+ "header_name": "请求头名称",
+ "credential": "凭证(加密存储)",
+ "connect": "连接",
+ "connected": "已连接",
+ "ready_to_connect": "可以连接",
+ "complete_before_enabling": "请先连接 MCP 并批准至少一个工具,再启用作用范围。",
+ "advanced": "高级配置",
+ "oauth_scope": "OAuth scopes(留空自动获取)",
+ "oauth_client_id": "OAuth client ID(留空自动注册)",
+ "oauth_client_secret": "OAuth client secret",
+ "oauth_authorization_endpoint": "Authorization endpoint 覆盖值",
+ "oauth_token_endpoint": "Token endpoint 覆盖值",
+ "oauth_token_auth_method": "Token endpoint 认证方式",
+ "oauth_token_auth_methods": {
+ "none": "公开客户端(PKCE)",
+ "client_secret_basic": "Client secret(HTTP Basic)",
+ "client_secret_post": "Client secret(请求体)"
+ },
+ "public_config": "公开配置(JSON 对象)",
+ "invalid_public_config": "公开配置必须是有效的 JSON 对象",
+ "failure_policy": "失败策略",
+ "failure_policies": {
+ "required": "必需 — 停止任务",
+ "optional": "可选 — 不使用工具并继续"
+ },
+ "configure_and_discover": "保存并发现工具",
+ "test": "测试连接",
+ "approve": "批准所选工具",
+ "revoke": "吊销凭证",
+ "credential_states": {
+ "configured": "已配置凭证",
+ "revoked": "凭证已吊销",
+ "missing": "缺少凭证",
+ "not_required": "无需凭证"
+ },
+ "reviewed": "工具已批准",
+ "pending_review": "需要批准",
+ "approved_tools": "已批准的工具",
+ "no_tools": "服务器未公布任何工具。",
+ "discovery": "已发现的工具 — 请明确审核访问权限",
+ "read": "读取",
+ "write": "写入",
+ "configured_success": "连接已保存;请审核已发现的工具",
+ "oauth_connected_success": "OAuth 连接已完成;请审核已发现的工具",
+ "oauth_connect_failed": "OAuth 连接未能完成,请重试。",
+ "test_success": "连接测试成功",
+ "approved_success": "工具访问权限已批准",
+ "revoked_success": "凭证已吊销,Plugin 已禁用"
}
},
"properties": {
diff --git a/packages/views/settings/components/plugins-tab.test.tsx b/packages/views/settings/components/plugins-tab.test.tsx
index d4a395d1ad..704d98de59 100644
--- a/packages/views/settings/components/plugins-tab.test.tsx
+++ b/packages/views/settings/components/plugins-tab.test.tsx
@@ -11,6 +11,13 @@ const mockSetEnabled = vi.hoisted(() => vi.fn());
const mockUpgrade = vi.hoisted(() => vi.fn());
const mockRollback = vi.hoisted(() => vi.fn());
const mockUninstall = vi.hoisted(() => vi.fn());
+const mockConfigureRemoteMCP = vi.hoisted(() => vi.fn());
+const mockTestRemoteMCP = vi.hoisted(() => vi.fn());
+const mockApproveRemoteMCP = vi.hoisted(() => vi.fn());
+const mockRevokeRemoteMCP = vi.hoisted(() => vi.fn());
+const mockStartRemoteMCPOAuth = vi.hoisted(() => vi.fn());
+const mockOpenExternal = vi.hoisted(() => vi.fn());
+const mockRefetch = vi.hoisted(() => vi.fn());
const data = vi.hoisted(() => ({
catalog: {
@@ -54,10 +61,10 @@ const data = vi.hoisted(() => ({
vi.mock("@tanstack/react-query", () => ({
useQuery: (options: { queryKey?: readonly string[] }) => {
const key = options.queryKey?.join(":") ?? "";
- if (key.includes("catalog")) return { data: data.catalog, isPending: false, isError: false };
- if (key.includes("installed")) return { data: data.installed, isPending: false, isError: false };
- if (key.includes("members")) return { data: data.members, isPending: false, isError: false };
- return { data: data.agents, isPending: false, isError: false };
+ if (key.includes("catalog")) return { data: data.catalog, isPending: false, isError: false, refetch: mockRefetch };
+ if (key.includes("installed")) return { data: data.installed, isPending: false, isError: false, refetch: mockRefetch };
+ if (key.includes("members")) return { data: data.members, isPending: false, isError: false, refetch: mockRefetch };
+ return { data: data.agents, isPending: false, isError: false, refetch: mockRefetch };
},
}));
@@ -70,8 +77,16 @@ vi.mock("@multica/core/plugins", () => ({
useUpgradePlugin: () => ({ mutateAsync: mockUpgrade, isPending: false }),
useRollbackPlugin: () => ({ mutateAsync: mockRollback, isPending: false }),
useUninstallPlugin: () => ({ mutateAsync: mockUninstall, isPending: false }),
+ useConfigurePluginRemoteMCP: () => ({ mutateAsync: mockConfigureRemoteMCP, isPending: false }),
+ useTestPluginRemoteMCP: () => ({ mutateAsync: mockTestRemoteMCP, isPending: false }),
+ useApprovePluginRemoteMCPTools: () => ({ mutateAsync: mockApproveRemoteMCP, isPending: false }),
+ useRevokePluginRemoteMCPCredential: () => ({ mutateAsync: mockRevokeRemoteMCP, isPending: false }),
+ useStartPluginRemoteMCPOAuth: () => ({ mutateAsync: mockStartRemoteMCPOAuth, isPending: false }),
}));
+vi.mock("../../platform/open-external", () => ({ openExternal: mockOpenExternal }));
+vi.mock("../../platform/local-directory", () => ({ isDesktopShell: () => true }));
+
vi.mock("@multica/core/workspace/queries", () => ({
agentListOptions: () => ({ queryKey: ["agents"] }),
memberListOptions: () => ({ queryKey: ["members"] }),
@@ -98,6 +113,7 @@ function Wrapper({ children }: { children: ReactNode }) {
describe("PluginsTab", () => {
beforeEach(() => {
vi.clearAllMocks();
+ window.history.replaceState({}, "", "/");
data.role = "owner";
data.catalog.releases[0]!.compatible = true;
data.catalog.releases[0]!.signature_verified = true;
@@ -105,6 +121,7 @@ describe("PluginsTab", () => {
mockInstall.mockResolvedValue({});
mockSetEnabled.mockResolvedValue({});
mockUninstall.mockResolvedValue({});
+ mockStartRemoteMCPOAuth.mockResolvedValue({ authorization_url: "https://auth.example.test/authorize" });
});
it("renders the install review and keeps installation disabled by default", async () => {
@@ -137,6 +154,7 @@ describe("PluginsTab", () => {
lifecycle_status: "installed",
contributions: ["review-readiness"],
bindings: [],
+ remote_mcp: [],
}];
render(<PluginsTab />, { wrapper: Wrapper });
@@ -202,6 +220,7 @@ describe("PluginsTab", () => {
entry_digest: "sha256:entry",
}],
bindings: [],
+ remote_mcp: [],
}];
render(<PluginsTab />, { wrapper: Wrapper });
@@ -213,4 +232,72 @@ describe("PluginsTab", () => {
await user.click(screen.getByRole("button", { name: "Uninstall" }));
await waitFor(() => expect(mockUninstall).toHaveBeenCalledWith("private-installation-1"));
});
+
+ it("opens OAuth in the platform browser and restores saved advanced configuration", async () => {
+ const user = userEvent.setup();
+ data.installed.plugins = [{
+ id: "private-remote-1",
+ plugin_key: "dev.acme.search",
+ display_name: "Search",
+ desired_version: "0.1.0",
+ active_version: "0.1.0",
+ enabled: false,
+ desired_generation: 1,
+ active_generation: 1,
+ lifecycle_status: "installed",
+ publisher: "acme.internal",
+ publisher_type: "private_dev",
+ trust_tier: "private_dev",
+ source_kind: "private_dev",
+ source_ref: "private://sha256:search",
+ signature_verified: false,
+ requested_capabilities: ["tool.remote-mcp.connect"],
+ available_versions: ["0.1.0"],
+ contributions: ["search"],
+ contribution_details: [],
+ bindings: [],
+ remote_mcp: [{
+ contribution_key: "search",
+ default_endpoint: "https://default.example.test/mcp",
+ preferred_auth: "oauth",
+ supported_auth: ["oauth"],
+ endpoint: "https://saved.example.test/mcp",
+ auth_type: "oauth",
+ public_config: { locale: "en" },
+ failure_policy: "optional",
+ credential_state: "missing",
+ approved_tools: [],
+ discovered_tools: [],
+ reviewed: false,
+ ready: false,
+ }],
+ }];
+ render(<PluginsTab />, { wrapper: Wrapper });
+
+ await user.click(screen.getByRole("button", { name: "Connect" }));
+ await waitFor(() => expect(mockStartRemoteMCPOAuth).toHaveBeenCalledWith(expect.objectContaining({
+ installationId: "private-remote-1",
+ contributionKey: "search",
+ request: expect.objectContaining({
+ endpoint: "https://saved.example.test/mcp",
+ public_config: { locale: "en" },
+ failure_policy: "optional",
+ }),
+ })));
+ expect(mockOpenExternal).toHaveBeenCalledWith("https://auth.example.test/authorize");
+
+ await user.click(screen.getByText("Advanced configuration"));
+ expect(screen.getByLabelText("HTTPS endpoint")).toHaveValue("https://saved.example.test/mcp");
+ expect(screen.getByLabelText("Public configuration (JSON object)")).toHaveValue('{\n "locale": "en"\n}');
+ });
+
+ it("consumes a successful OAuth callback and refreshes installation state", async () => {
+ window.history.replaceState({}, "", "/settings?tab=plugins&remote_mcp_connected=1#plugins");
+
+ render(<PluginsTab />, { wrapper: Wrapper });
+
+ await waitFor(() => expect(mockRefetch).toHaveBeenCalled());
+ expect(window.location.search).toBe("?tab=plugins");
+ expect(window.location.hash).toBe("#plugins");
+ });
});
diff --git a/packages/views/settings/components/plugins-tab.tsx b/packages/views/settings/components/plugins-tab.tsx
index e3c119dff8..02ef690775 100644
--- a/packages/views/settings/components/plugins-tab.tsx
+++ b/packages/views/settings/components/plugins-tab.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { AlertCircle, CheckCircle2, Loader2, PackageCheck, ShieldCheck, Trash2 } from "lucide-react";
import { toast } from "sonner";
@@ -10,17 +10,29 @@ import {
comparePluginVersions,
pluginCatalogOptions,
pluginInstallationsOptions,
+ useApprovePluginRemoteMCPTools,
+ useConfigurePluginRemoteMCP,
useInstallPlugin,
+ useRevokePluginRemoteMCPCredential,
useRollbackPlugin,
useSetPluginEnabled,
+ useTestPluginRemoteMCP,
+ useStartPluginRemoteMCPOAuth,
useUninstallPlugin,
useUpgradePlugin,
} from "@multica/core/plugins";
import { useCurrentWorkspace } from "@multica/core/paths";
-import type { PluginCatalogRelease, PluginInstallation } from "@multica/core/types";
+import type {
+ PluginCatalogRelease,
+ PluginInstallation,
+ PluginRemoteMCPConfig,
+ RemoteMCPDiscoveryResponse,
+} 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 { Input } from "@multica/ui/components/ui/input";
import {
Select,
SelectContent,
@@ -29,11 +41,383 @@ import {
SelectValue,
} from "@multica/ui/components/ui/select";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import { Textarea } from "@multica/ui/components/ui/textarea";
import { useT } from "../../i18n";
+import { isDesktopShell } from "../../platform/local-directory";
+import { openExternal } from "../../platform/open-external";
import { SettingsCard, SettingsSection, SettingsTab } from "./settings-layout";
type BindingScope = "workspace" | "agent";
+type RemoteMCPAuthType = "none" | "oauth" | "bearer" | "header";
+
+function RemoteMCPConfiguration({
+ wsId,
+ installationId,
+ config,
+ canManage,
+}: {
+ wsId: string;
+ installationId: string;
+ config: PluginRemoteMCPConfig;
+ canManage: boolean;
+}) {
+ const { t } = useT("settings");
+ const configureMutation = useConfigurePluginRemoteMCP(wsId);
+ const testMutation = useTestPluginRemoteMCP(wsId);
+ const approveMutation = useApprovePluginRemoteMCPTools(wsId);
+ const revokeMutation = useRevokePluginRemoteMCPCredential(wsId);
+ const oauthMutation = useStartPluginRemoteMCPOAuth(wsId);
+ const [endpoint, setEndpoint] = useState(config.endpoint ?? config.default_endpoint ?? "");
+ const [authType, setAuthType] = useState<RemoteMCPAuthType>(
+ config.auth_type === "oauth" || config.auth_type === "bearer" || config.auth_type === "header" || config.auth_type === "none"
+ ? config.auth_type
+ : config.preferred_auth === "oauth" ? "oauth" : "none",
+ );
+ const [authHeader, setAuthHeader] = useState(config.auth_header ?? "Authorization");
+ const [credential, setCredential] = useState("");
+ const [oauthScope, setOAuthScope] = useState("");
+ const [oauthClientId, setOAuthClientId] = useState("");
+ const [oauthClientSecret, setOAuthClientSecret] = useState("");
+ const [oauthAuthorizationEndpoint, setOAuthAuthorizationEndpoint] = useState("");
+ const [oauthTokenEndpoint, setOAuthTokenEndpoint] = useState("");
+ const [oauthTokenAuthMethod, setOAuthTokenAuthMethod] = useState<"none" | "client_secret_basic" | "client_secret_post">("none");
+ const [publicConfig, setPublicConfig] = useState(() => JSON.stringify(config.public_config ?? {}, null, 2));
+ const [failurePolicy, setFailurePolicy] = useState<"required" | "optional">(
+ config.failure_policy === "optional" ? "optional" : "required",
+ );
+ const [discovery, setDiscovery] = useState<RemoteMCPDiscoveryResponse | null>(() =>
+ !config.reviewed && config.discovered_tools.length > 0
+ ? {
+ config_revision: config.config_revision ?? 0,
+ discovered_tools: config.discovered_tools,
+ discovered_schema_digest: config.discovered_schema_digest ?? "",
+ }
+ : null,
+ );
+ const [approvedTools, setApprovedTools] = useState<string[]>(() =>
+ !config.reviewed ? config.discovered_tools.map((tool) => tool.name) : [],
+ );
+ const isPending = configureMutation.isPending || testMutation.isPending
+ || approveMutation.isPending || revokeMutation.isPending || oauthMutation.isPending;
+ const isConnected = Boolean(config.config_revision)
+ && (config.credential_state === "configured" || config.credential_state === "not_required");
+
+ const reportError = (error: unknown) => {
+ toast.error(error instanceof Error ? error.message : t(($) => $.plugins.action_failed));
+ };
+ const rememberDiscovery = (result: RemoteMCPDiscoveryResponse) => {
+ setDiscovery(result);
+ setApprovedTools(result.discovered_tools.map((tool) => tool.name));
+ };
+ const credentialStateLabel = config.credential_state === "configured"
+ ? t(($) => $.plugins.remote_mcp.credential_states.configured)
+ : config.credential_state === "revoked"
+ ? t(($) => $.plugins.remote_mcp.credential_states.revoked)
+ : config.credential_state === "not_required"
+ ? t(($) => $.plugins.remote_mcp.credential_states.not_required)
+ : t(($) => $.plugins.remote_mcp.credential_states.missing);
+ const configure = async (requestedAuth: RemoteMCPAuthType = authType) => {
+ let parsedPublicConfig: Record<string, unknown>;
+ try {
+ const parsed: unknown = JSON.parse(publicConfig);
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error();
+ parsedPublicConfig = parsed as Record<string, unknown>;
+ } catch {
+ toast.error(t(($) => $.plugins.remote_mcp.invalid_public_config));
+ return;
+ }
+ try {
+ if (requestedAuth === "oauth") {
+ const result = await oauthMutation.mutateAsync({
+ installationId,
+ contributionKey: config.contribution_key,
+ request: {
+ endpoint: endpoint.trim() || config.default_endpoint,
+ public_config: parsedPublicConfig,
+ failure_policy: failurePolicy,
+ scope: oauthScope.trim() || undefined,
+ client_id: oauthClientId.trim() || undefined,
+ client_secret: oauthClientSecret || undefined,
+ token_endpoint_auth_method: oauthClientId.trim() ? oauthTokenAuthMethod : undefined,
+ authorization_endpoint: oauthAuthorizationEndpoint.trim() || undefined,
+ token_endpoint: oauthTokenEndpoint.trim() || undefined,
+ return_to: `${window.location.pathname}${window.location.search}`,
+ },
+ });
+ if (!result.authorization_url) {
+ throw new Error(t(($) => $.plugins.remote_mcp.oauth_connect_failed));
+ }
+ if (isDesktopShell()) {
+ openExternal(result.authorization_url);
+ } else {
+ window.location.assign(result.authorization_url);
+ }
+ return;
+ }
+ const result = await configureMutation.mutateAsync({
+ installationId,
+ contributionKey: config.contribution_key,
+ request: {
+ endpoint: endpoint.trim(),
+ public_config: parsedPublicConfig,
+ auth_type: requestedAuth,
+ auth_header: requestedAuth === "header" ? authHeader.trim() : undefined,
+ credential: requestedAuth === "none" ? undefined : credential,
+ failure_policy: failurePolicy,
+ },
+ });
+ setCredential("");
+ rememberDiscovery(result);
+ toast.success(t(($) => $.plugins.remote_mcp.configured_success));
+ } catch (error) {
+ reportError(error);
+ }
+ };
+
+ return (
+ <div className="space-y-4 rounded-xl border border-surface-border bg-muted/30 p-4">
+ <div className="flex flex-wrap items-start justify-between gap-2">
+ <div>
+ <div className="text-body font-medium">{t(($) => $.plugins.remote_mcp.title)} · {config.contribution_key}</div>
+ <div className="mt-1 flex flex-wrap items-center gap-2 text-caption text-muted-foreground">
+ {config.endpoint_domain ? <span>{config.endpoint_domain}</span> : null}
+ <Badge variant={config.credential_state === "revoked" || config.credential_state === "missing" ? "destructive" : "secondary"}>
+ {credentialStateLabel}
+ </Badge>
+ <Badge variant={config.reviewed ? "default" : "secondary"}>
+ {config.reviewed ? t(($) => $.plugins.remote_mcp.reviewed) : t(($) => $.plugins.remote_mcp.pending_review)}
+ </Badge>
+ {config.credential_hint ? <span>{config.credential_hint}</span> : null}
+ </div>
+ </div>
+ {config.credential_state !== "not_required" ? (
+ <Button
+ size="xs"
+ variant="ghost"
+ disabled={!canManage || isPending || config.credential_state !== "configured"}
+ onClick={() => revokeMutation.mutateAsync({ installationId, contributionKey: config.contribution_key })
+ .then(() => toast.success(t(($) => $.plugins.remote_mcp.revoked_success)))
+ .catch(reportError)}
+ >
+ {t(($) => $.plugins.remote_mcp.revoke)}
+ </Button>
+ ) : null}
+ </div>
+
+ {config.default_endpoint && (config.preferred_auth === "oauth" || config.preferred_auth === "none") ? (
+ <div className="flex flex-wrap items-center gap-3 rounded-lg border border-surface-border bg-background p-3">
+ <div className="min-w-0 flex-1">
+ <div className="text-caption font-medium">
+ {isConnected ? t(($) => $.plugins.remote_mcp.connected) : t(($) => $.plugins.remote_mcp.ready_to_connect)}
+ </div>
+ <div className="mt-0.5 truncate text-caption text-muted-foreground">{config.default_endpoint}</div>
+ </div>
+ <Button
+ size="sm"
+ disabled={!canManage || isPending || isConnected}
+ onClick={() => configure(config.preferred_auth as RemoteMCPAuthType)}
+ >
+ {oauthMutation.isPending || configureMutation.isPending ? <Loader2 className="animate-spin" /> : null}
+ {isConnected ? t(($) => $.plugins.remote_mcp.connected) : t(($) => $.plugins.remote_mcp.connect)}
+ </Button>
+ </div>
+ ) : null}
+
+ <details className="group rounded-lg border border-surface-border bg-background">
+ <summary className="cursor-pointer select-none px-3 py-2 text-caption font-medium">
+ {t(($) => $.plugins.remote_mcp.advanced)}
+ </summary>
+ <div className="grid gap-3 border-t border-surface-border p-3 sm:grid-cols-2">
+ <label className="space-y-1 text-caption sm:col-span-2">
+ <span className="font-medium">{t(($) => $.plugins.remote_mcp.endpoint)}</span>
+ <Input
+ value={endpoint}
+ onChange={(event) => setEndpoint(event.target.value)}
+ placeholder={t(($) => $.plugins.remote_mcp.endpoint_placeholder)}
+ disabled={!canManage || isPending}
+ />
+ </label>
+ <label className="space-y-1 text-caption">
+ <span className="font-medium">{t(($) => $.plugins.remote_mcp.auth)}</span>
+ <Select
+ items={(["none", "oauth", "bearer", "header"] as const).map((value) => ({
+ value,
+ label: t(($) => $.plugins.remote_mcp.auth_types[value]),
+ }))}
+ value={authType}
+ onValueChange={(value) => value && setAuthType(value as RemoteMCPAuthType)}
+ disabled={!canManage || isPending}
+ >
+ <SelectTrigger><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">{t(($) => $.plugins.remote_mcp.auth_types.none)}</SelectItem>
+ <SelectItem value="oauth">{t(($) => $.plugins.remote_mcp.auth_types.oauth)}</SelectItem>
+ <SelectItem value="bearer">{t(($) => $.plugins.remote_mcp.auth_types.bearer)}</SelectItem>
+ <SelectItem value="header">{t(($) => $.plugins.remote_mcp.auth_types.header)}</SelectItem>
+ </SelectContent>
+ </Select>
+ </label>
+ <label className="space-y-1 text-caption">
+ <span className="font-medium">{t(($) => $.plugins.remote_mcp.failure_policy)}</span>
+ <Select
+ items={(["required", "optional"] as const).map((value) => ({
+ value,
+ label: t(($) => $.plugins.remote_mcp.failure_policies[value]),
+ }))}
+ value={failurePolicy}
+ onValueChange={(value) => value && setFailurePolicy(value as "required" | "optional")}
+ disabled={!canManage || isPending}
+ >
+ <SelectTrigger><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="required">{t(($) => $.plugins.remote_mcp.failure_policies.required)}</SelectItem>
+ <SelectItem value="optional">{t(($) => $.plugins.remote_mcp.failure_policies.optional)}</SelectItem>
+ </SelectContent>
+ </Select>
+ </label>
+ {authType === "header" ? (
+ <label className="space-y-1 text-caption">
+ <span className="font-medium">{t(($) => $.plugins.remote_mcp.header_name)}</span>
+ <Input value={authHeader} onChange={(event) => setAuthHeader(event.target.value)} disabled={!canManage || isPending} />
+ </label>
+ ) : null}
+ {authType === "bearer" || authType === "header" ? (
+ <label className="space-y-1 text-caption">
+ <span className="font-medium">{t(($) => $.plugins.remote_mcp.credential)}</span>
+ <Input
+ type="password"
+ autoComplete="new-password"
+ value={credential}
+ onChange={(event) => setCredential(event.target.value)}
+ disabled={!canManage || isPending}
+ />
+ </label>
+ ) : null}
+ {authType === "oauth" ? (
+ <>
+ <label className="space-y-1 text-caption sm:col-span-2">
+ <span className="font-medium">{t(($) => $.plugins.remote_mcp.oauth_scope)}</span>
+ <Input value={oauthScope} onChange={(event) => setOAuthScope(event.target.value)} disabled={!canManage || isPending} />
+ </label>
+ <label className="space-y-1 text-caption">
+ <span className="font-medium">{t(($) => $.plugins.remote_mcp.oauth_client_id)}</span>
+ <Input value={oauthClientId} onChange={(event) => setOAuthClientId(event.target.value)} disabled={!canManage || isPending} />
+ </label>
+ <label className="space-y-1 text-caption">
+ <span className="font-medium">{t(($) => $.plugins.remote_mcp.oauth_client_secret)}</span>
+ <Input type="password" autoComplete="new-password" value={oauthClientSecret} onChange={(event) => setOAuthClientSecret(event.target.value)} disabled={!canManage || isPending} />
+ </label>
+ <label className="space-y-1 text-caption">
+ <span className="font-medium">{t(($) => $.plugins.remote_mcp.oauth_authorization_endpoint)}</span>
+ <Input value={oauthAuthorizationEndpoint} onChange={(event) => setOAuthAuthorizationEndpoint(event.target.value)} disabled={!canManage || isPending} />
+ </label>
+ <label className="space-y-1 text-caption">
+ <span className="font-medium">{t(($) => $.plugins.remote_mcp.oauth_token_endpoint)}</span>
+ <Input value={oauthTokenEndpoint} onChange={(event) => setOAuthTokenEndpoint(event.target.value)} disabled={!canManage || isPending} />
+ </label>
+ {oauthClientSecret ? (
+ <label className="space-y-1 text-caption sm:col-span-2">
+ <span className="font-medium">{t(($) => $.plugins.remote_mcp.oauth_token_auth_method)}</span>
+ <Select
+ items={(["none", "client_secret_basic", "client_secret_post"] as const).map((value) => ({ value, label: value }))}
+ value={oauthTokenAuthMethod}
+ onValueChange={(value) => value && setOAuthTokenAuthMethod(value as typeof oauthTokenAuthMethod)}
+ disabled={!canManage || isPending}
+ >
+ <SelectTrigger><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">{t(($) => $.plugins.remote_mcp.oauth_token_auth_methods.none)}</SelectItem>
+ <SelectItem value="client_secret_basic">{t(($) => $.plugins.remote_mcp.oauth_token_auth_methods.client_secret_basic)}</SelectItem>
+ <SelectItem value="client_secret_post">{t(($) => $.plugins.remote_mcp.oauth_token_auth_methods.client_secret_post)}</SelectItem>
+ </SelectContent>
+ </Select>
+ </label>
+ ) : null}
+ </>
+ ) : null}
+ <label className="space-y-1 text-caption sm:col-span-2">
+ <span className="font-medium">{t(($) => $.plugins.remote_mcp.public_config)}</span>
+ <Textarea
+ className="font-mono"
+ value={publicConfig}
+ onChange={(event) => setPublicConfig(event.target.value)}
+ disabled={!canManage || isPending}
+ />
+ </label>
+ </div>
+
+ <div className="flex flex-wrap gap-2 border-t border-surface-border p-3">
+ <Button
+ size="sm"
+ disabled={!canManage || isPending || endpoint.trim() === "" || ((authType === "bearer" || authType === "header") && credential === "")}
+ onClick={() => configure()}
+ >
+ {configureMutation.isPending || oauthMutation.isPending ? <Loader2 className="animate-spin" /> : null}
+ {t(($) => $.plugins.remote_mcp.configure_and_discover)}
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={!canManage || isPending || !config.config_revision}
+ onClick={() => testMutation.mutateAsync({ installationId, contributionKey: config.contribution_key })
+ .then((result) => {
+ rememberDiscovery(result);
+ toast.success(t(($) => $.plugins.remote_mcp.test_success));
+ }).catch(reportError)}
+ >
+ {testMutation.isPending ? <Loader2 className="animate-spin" /> : null}
+ {t(($) => $.plugins.remote_mcp.test)}
+ </Button>
+ </div>
+ </details>
+
+ {discovery ? (
+ <div className="space-y-3 border-t border-surface-border pt-3">
+ <div className="text-caption font-medium">{t(($) => $.plugins.remote_mcp.discovery)}</div>
+ {discovery.discovered_tools.length > 0 ? discovery.discovered_tools.map((tool) => (
+ <label key={tool.name} className="flex items-start gap-2 rounded-lg bg-background px-3 py-2 text-caption">
+ <Checkbox
+ checked={approvedTools.includes(tool.name)}
+ disabled={!canManage || isPending}
+ onCheckedChange={() => setApprovedTools((current) => current.includes(tool.name)
+ ? current.filter((name) => name !== tool.name)
+ : [...current, tool.name])}
+ />
+ <span className="min-w-0">
+ <span className="font-medium">{tool.name}</span>
+ <Badge className="ml-2" variant={tool.risk === "write" ? "destructive" : "secondary"}>
+ {tool.risk === "write" ? t(($) => $.plugins.remote_mcp.write) : t(($) => $.plugins.remote_mcp.read)}
+ </Badge>
+ {tool.description ? <span className="mt-0.5 block text-muted-foreground">{tool.description}</span> : null}
+ </span>
+ </label>
+ )) : <p className="text-caption text-muted-foreground">{t(($) => $.plugins.remote_mcp.no_tools)}</p>}
+ <Button
+ size="sm"
+ disabled={!canManage || isPending || approvedTools.length === 0}
+ onClick={() => approveMutation.mutateAsync({
+ installationId,
+ contributionKey: config.contribution_key,
+ tools: approvedTools,
+ }).then(() => {
+ setDiscovery(null);
+ toast.success(t(($) => $.plugins.remote_mcp.approved_success));
+ }).catch(reportError)}
+ >
+ {approveMutation.isPending ? <Loader2 className="animate-spin" /> : <ShieldCheck />}
+ {t(($) => $.plugins.remote_mcp.approve)}
+ </Button>
+ </div>
+ ) : config.approved_tools.length > 0 ? (
+ <div className="text-caption text-muted-foreground">
+ {t(($) => $.plugins.remote_mcp.approved_tools)}: {config.approved_tools.map((tool) => tool.name).join(", ")}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
function installationState(installation: PluginInstallation): "disabled" | "activating" | "healthy" | "degraded" | "failed" {
if (installation.enabled !== true) return "disabled";
if (installation.lifecycle_status === "activating") return "activating";
@@ -50,6 +434,7 @@ export function PluginsTab() {
const canManage = currentMember.role === "owner" || currentMember.role === "admin";
const catalogQuery = useQuery(pluginCatalogOptions(wsId));
const installationsQuery = useQuery(pluginInstallationsOptions(wsId));
+ const refetchInstallations = installationsQuery.refetch;
const agentsQuery = useQuery(agentListOptions(wsId));
const membersQuery = useQuery(memberListOptions(wsId));
const installMutation = useInstallPlugin(wsId);
@@ -61,6 +446,24 @@ export function PluginsTab() {
const [selectedScopes, setSelectedScopes] = useState<Record<string, BindingScope>>({});
const [selectedAgents, setSelectedAgents] = useState<Record<string, string>>({});
+ useEffect(() => {
+ const search = new URLSearchParams(window.location.search);
+ const connected = search.get("remote_mcp_connected") === "1";
+ const failed = search.has("remote_mcp_error");
+ if (!connected && !failed) return;
+
+ if (connected) {
+ toast.success(t(($) => $.plugins.remote_mcp.oauth_connected_success));
+ void refetchInstallations();
+ } else {
+ toast.error(t(($) => $.plugins.remote_mcp.oauth_connect_failed));
+ }
+ search.delete("remote_mcp_connected");
+ search.delete("remote_mcp_error");
+ const query = search.toString();
+ window.history.replaceState(window.history.state, "", `${window.location.pathname}${query ? `?${query}` : ""}${window.location.hash}`);
+ }, [refetchInstallations, t]);
+
const releasesByPlugin = useMemo(() => {
const grouped = new Map<string, PluginCatalogRelease[]>();
for (const release of catalogQuery.data?.releases ?? []) {
@@ -170,6 +573,7 @@ export function PluginsTab() {
const state = installation ? installationState(installation) : null;
const activeBindings = installation?.bindings.filter((binding) => binding.enabled === true) ?? [];
const workspaceBindingActive = activeBindings.some((binding) => binding.scope_type === "workspace");
+ const remoteMCPReady = installation?.remote_mcp.every((config) => config.ready) ?? true;
return (
<SettingsSection key={pluginKey}>
@@ -273,6 +677,16 @@ export function PluginsTab() {
<span>{t(($) => $.plugins.health)} {installation.health_state || installation.lifecycle_status}</span>
</div>
+ {installation.remote_mcp.map((config) => (
+ <RemoteMCPConfiguration
+ key={config.contribution_key}
+ wsId={wsId}
+ installationId={installation.id}
+ config={config}
+ canManage={canManage}
+ />
+ ))}
+
{activeBindings.length > 0 ? (
<div className="space-y-2">
<div className="text-caption font-medium">{t(($) => $.plugins.bindings)}</div>
@@ -303,6 +717,12 @@ export function PluginsTab() {
<p className="text-caption text-muted-foreground">{t(($) => $.plugins.no_bindings)}</p>
)}
+ {!remoteMCPReady ? (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.plugins.remote_mcp.complete_before_enabling)}
+ </p>
+ ) : null}
+
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
<Select
items={[
@@ -331,7 +751,7 @@ export function PluginsTab() {
</Select>
) : null}
<Button
- disabled={!canManage || isMutating || (scope === "agent" && !selectedAgent)}
+ disabled={!canManage || isMutating || !remoteMCPReady || (scope === "agent" && !selectedAgent)}
onClick={() => enabledMutation.mutateAsync({
installationId: installation.id,
enabled: true,
@@ -407,6 +827,7 @@ export function PluginsTab() {
const selectedAgent = selectedAgents[installation.id] ?? agents[0]?.id ?? "";
const state = installationState(installation);
const activeBindings = installation.bindings.filter((binding) => binding.enabled === true);
+ const remoteMCPReady = installation.remote_mcp.every((config) => config.ready);
const uploaderName = members.find((member) => member.user_id === installation.uploader_id)?.name;
const rollbackVersion = [...installation.available_versions]
.sort((left, right) => comparePluginVersions(right, left))
@@ -471,6 +892,16 @@ export function PluginsTab() {
<span>{t(($) => $.plugins.health)} {installation.health_state || installation.lifecycle_status}</span>
</div>
+ {installation.remote_mcp.map((config) => (
+ <RemoteMCPConfiguration
+ key={config.contribution_key}
+ wsId={wsId}
+ installationId={installation.id}
+ config={config}
+ canManage={canManage}
+ />
+ ))}
+
{activeBindings.length > 0 ? (
<div className="space-y-2">
<div className="text-caption font-medium">{t(($) => $.plugins.bindings)}</div>
@@ -499,6 +930,12 @@ export function PluginsTab() {
</div>
) : <p className="text-caption text-muted-foreground">{t(($) => $.plugins.no_bindings)}</p>}
+ {!remoteMCPReady ? (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.plugins.remote_mcp.complete_before_enabling)}
+ </p>
+ ) : null}
+
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
<Select
items={[
@@ -527,7 +964,7 @@ export function PluginsTab() {
</Select>
) : null}
<Button
- disabled={!canManage || isMutating || (scope === "agent" && !selectedAgent)}
+ disabled={!canManage || isMutating || !remoteMCPReady || (scope === "agent" && !selectedAgent)}
onClick={() => enabledMutation.mutateAsync({
installationId: installation.id,
enabled: true,
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 51336bd390..ba3c5a112d 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -104,6 +104,11 @@ var concurrentIndexCleanups = map[string]string{
"306_dingtalk_group_route_workspace_index": "idx_dingtalk_group_route_workspace",
"307_dingtalk_group_route_id_unique": "idx_dingtalk_group_route_id_unique",
"311_plugin_identity_scoped_key_index": "idx_plugin_identity_scoped_key",
+ "320_plugin_installation_config_revision_index": "idx_plugin_installation_config_contribution_revision",
+ "321_plugin_installation_config_workspace_index": "idx_plugin_installation_config_workspace",
+ "322_plugin_remote_mcp_secret_revision_index": "idx_plugin_remote_mcp_secret_revision",
+ "323_plugin_remote_mcp_secret_workspace_index": "idx_plugin_remote_mcp_secret_workspace",
+ "324_plugin_remote_mcp_one_active_secret_index": "idx_plugin_remote_mcp_one_active_secret",
}
// concurrentDownIndexCleanups covers every migration whose down direction
diff --git a/server/cmd/multica/cmd_plugin.go b/server/cmd/multica/cmd_plugin.go
index 18aa0aee5d..cc1be8a96a 100644
--- a/server/cmd/multica/cmd_plugin.go
+++ b/server/cmd/multica/cmd_plugin.go
@@ -4,9 +4,11 @@ import (
"context"
"encoding/json"
"fmt"
+ "io"
"net/url"
"os"
"path/filepath"
+ "strings"
"time"
"github.com/spf13/cobra"
@@ -59,11 +61,29 @@ var pluginStatusCmd = &cobra.Command{
RunE: runPluginStatus,
}
+var pluginRemoteMCPCmd = &cobra.Command{Use: "remote-mcp", Short: "Configure and review Remote MCP contributions"}
+
+var pluginRemoteMCPConfigureCmd = &cobra.Command{
+ Use: "configure <installation-id> <contribution-key>", Short: "Configure and test a Remote MCP endpoint", Args: exactArgs(2), RunE: runPluginRemoteMCPConfigure,
+}
+var pluginRemoteMCPTestCmd = &cobra.Command{
+ Use: "test <installation-id> <contribution-key>", Short: "Test and discover a configured Remote MCP endpoint", Args: exactArgs(2), RunE: runPluginRemoteMCPTest,
+}
+var pluginRemoteMCPApproveCmd = &cobra.Command{
+ Use: "approve <installation-id> <contribution-key>", Short: "Approve an explicit Remote MCP tool allowlist", Args: exactArgs(2), RunE: runPluginRemoteMCPApprove,
+}
+var pluginRemoteMCPRevokeCmd = &cobra.Command{
+ Use: "revoke <installation-id> <contribution-key>", Short: "Revoke the Remote MCP credential and disable the Plugin", Args: exactArgs(2), RunE: runPluginRemoteMCPRevoke,
+}
+
func init() {
- pluginCmd.AddCommand(pluginInitCmd, pluginValidateCmd, pluginPackCmd, pluginInstallCmd, pluginListCmd, pluginStatusCmd)
+ pluginCmd.AddCommand(pluginInitCmd, pluginValidateCmd, pluginPackCmd, pluginInstallCmd, pluginListCmd, pluginStatusCmd, pluginRemoteMCPCmd)
+ pluginRemoteMCPCmd.AddCommand(pluginRemoteMCPConfigureCmd, pluginRemoteMCPTestCmd, pluginRemoteMCPApproveCmd, pluginRemoteMCPRevokeCmd)
pluginInitCmd.Flags().String("key", "dev.local.example-skill", "Reverse-DNS Plugin key")
pluginInitCmd.Flags().String("name", "Example Skill", "Plugin and Skill display name")
pluginInitCmd.Flags().String("publisher", "private.local", "Private publisher label")
+ pluginInitCmd.Flags().String("contribution", "skill", "Contribution template: skill or remote-mcp")
+ pluginInitCmd.Flags().String("endpoint-host", "mcp.example.com", "Allowed Remote MCP endpoint host for the remote-mcp template")
pluginValidateCmd.Flags().String("output", "json", "Output format: table or json")
pluginPackCmd.Flags().String("output", "", "Output ZIP path (required)")
pluginPackCmd.Flags().String("format", "table", "Result format: table or json")
@@ -73,6 +93,18 @@ func init() {
pluginListCmd.Flags().String("output", "table", "Output format: table or json")
pluginStatusCmd.Flags().String("workspace", "", "Workspace ID, slug, or ID prefix")
pluginStatusCmd.Flags().String("output", "json", "Output format: table or json")
+ for _, command := range []*cobra.Command{pluginRemoteMCPConfigureCmd, pluginRemoteMCPTestCmd, pluginRemoteMCPApproveCmd, pluginRemoteMCPRevokeCmd} {
+ command.Flags().String("workspace", "", "Workspace ID, slug, or ID prefix")
+ command.Flags().String("output", "json", "Output format: json")
+ }
+ pluginRemoteMCPConfigureCmd.Flags().String("endpoint", "", "Public HTTPS MCP endpoint (required)")
+ pluginRemoteMCPConfigureCmd.Flags().String("auth-type", "none", "Authentication: none, bearer, or header")
+ pluginRemoteMCPConfigureCmd.Flags().String("auth-header", "", "Header name when --auth-type=header")
+ pluginRemoteMCPConfigureCmd.Flags().Bool("credential-stdin", false, "Read the credential from stdin; keeps it out of shell history and ps")
+ pluginRemoteMCPConfigureCmd.Flags().String("credential-file", "", "Read the credential from a file (suggested mode: 0600)")
+ pluginRemoteMCPConfigureCmd.Flags().String("public-config-file", "", "Read non-secret public configuration JSON from a file")
+ pluginRemoteMCPConfigureCmd.Flags().String("failure-policy", "required", "Failure policy: required or optional")
+ pluginRemoteMCPApproveCmd.Flags().StringSlice("tool", nil, "Tool name to approve (repeatable or comma-separated; required)")
}
func runPluginInit(cmd *cobra.Command, args []string) error {
@@ -87,23 +119,47 @@ func runPluginInit(cmd *cobra.Command, args []string) error {
key, _ := cmd.Flags().GetString("key")
name, _ := cmd.Flags().GetString("name")
publisher, _ := cmd.Flags().GetString("publisher")
+ contributionType, _ := cmd.Flags().GetString("contribution")
+ endpointHost, _ := cmd.Flags().GetString("endpoint-host")
+ if contributionType == "" {
+ contributionType = "skill"
+ }
+ if endpointHost == "" {
+ endpointHost = "mcp.example.com"
+ }
manifest := plugincontract.Manifest{
APIVersion: plugincontract.APIVersionV1,
Kind: plugincontract.KindPlugin,
Metadata: plugincontract.Metadata{
Key: key, Name: name, Description: "A workspace-private declarative Skill Plugin.", Version: "0.1.0", Publisher: publisher,
},
- Compatibility: plugincontract.Compatibility{
- HostAPI: ">=1.0.0 <2.0.0",
- RequiredDaemonFeatures: []string{
- plugincontract.DaemonFeatureExecutionManifestV1,
- plugincontract.DaemonFeatureAgentSkillV1,
- },
- },
- RequestedCapabilities: []string{plugincontract.CapabilityAgentSkillContribute},
- Contributes: plugincontract.ManifestContributions{AgentSkills: []plugincontract.AgentSkillContribution{{
+ Compatibility: plugincontract.Compatibility{HostAPI: ">=1.0.0 <2.0.0"},
+ }
+ switch contributionType {
+ case "skill":
+ manifest.Compatibility.RequiredDaemonFeatures = []string{plugincontract.DaemonFeatureExecutionManifestV1, plugincontract.DaemonFeatureAgentSkillV1}
+ manifest.RequestedCapabilities = []string{plugincontract.CapabilityAgentSkillContribute}
+ manifest.Contributes.AgentSkills = []plugincontract.AgentSkillContribution{{
Key: "example-skill", Name: name, Description: "Explain when and how this Skill should be used.", Entry: "skills/example-skill/SKILL.md",
- }}},
+ }}
+ case "remote-mcp":
+ manifest.Metadata.Description = "A workspace-private declarative Remote MCP Plugin."
+ manifest.Compatibility.RequiredDaemonFeatures = []string{plugincontract.DaemonFeatureExecutionManifestV1, plugincontract.DaemonFeatureRemoteMCPV1}
+ manifest.RequestedCapabilities = []string{plugincontract.CapabilityRemoteMCPConnect}
+ manifest.Contributes.RemoteMCP = []plugincontract.RemoteMCPContribution{{
+ Key: "example-tools", Name: name, Description: "Expose explicitly reviewed remote tools.",
+ Transport: "streamable-http", ProtocolVersions: []string{"2025-03-26", "2024-11-05"},
+ EndpointPolicy: plugincontract.RemoteMCPEndpointPolicy{
+ DefaultEndpoint: "https://" + endpointHost + "/mcp", AllowedHosts: []string{endpointHost},
+ },
+ Authentication: plugincontract.RemoteMCPAuthentication{
+ Preferred: "oauth", Supported: []string{"oauth", "bearer", "header", "none"},
+ },
+ ToolIntent: []plugincontract.RemoteMCPToolIntent{{Name: "example.read", Description: "Read an example value.", Risk: "read"}},
+ ConfigurationSchema: json.RawMessage(`{"type":"object","additionalProperties":false}`),
+ }}
+ default:
+ return fmt.Errorf("--contribution must be skill or remote-mcp")
}
manifestBytes, err := json.MarshalIndent(manifest, "", " ")
if err != nil {
@@ -113,15 +169,20 @@ func runPluginInit(cmd *cobra.Command, args []string) error {
if _, _, err := plugincontract.ParseManifest(manifestBytes); err != nil {
return err
}
- if err := os.MkdirAll(filepath.Join(dir, "skills", "example-skill"), 0o755); err != nil {
+ if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(dir, plugincontract.ManifestFilename), manifestBytes, 0o644); err != nil {
return err
}
- skill := []byte("---\nname: example-skill\ndescription: Explain when this Skill should be used.\n---\n\n# Example Skill\n\nDescribe the declarative instructions the Agent should follow.\n")
- if err := os.WriteFile(filepath.Join(dir, "skills", "example-skill", "SKILL.md"), skill, 0o644); err != nil {
- return err
+ if contributionType == "skill" {
+ if err := os.MkdirAll(filepath.Join(dir, "skills", "example-skill"), 0o755); err != nil {
+ return err
+ }
+ skill := []byte("---\nname: example-skill\ndescription: Explain when this Skill should be used.\n---\n\n# Example Skill\n\nDescribe the declarative instructions the Agent should follow.\n")
+ if err := os.WriteFile(filepath.Join(dir, "skills", "example-skill", "SKILL.md"), skill, 0o644); err != nil {
+ return err
+ }
}
fmt.Fprintf(cmd.OutOrStdout(), "Initialized Private Plugin in %s\n", dir)
return nil
@@ -325,3 +386,105 @@ func runPluginStatus(cmd *cobra.Command, args []string) error {
}
return printPluginRows(cmd, plugins)
}
+
+func remoteMCPAPI(cmd *cobra.Command, args []string, suffix string, method string, body any) error {
+ if err := requireHumanLocalCommand("plugin remote-mcp " + method); err != nil {
+ return err
+ }
+ workspaceID, err := pluginWorkspaceID(cmd)
+ if err != nil {
+ return err
+ }
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ client.WorkspaceID = workspaceID
+ path := "/api/workspaces/" + workspaceID + "/plugins/" + url.PathEscape(args[0]) + "/remote-mcp/" + url.PathEscape(args[1]) + suffix
+ ctx, cancel := context.WithTimeout(context.Background(), cli.AtLeastAPITimeout(time.Minute))
+ defer cancel()
+ if method == "revoke" {
+ if err := client.DeleteJSON(ctx, path); err != nil {
+ return err
+ }
+ return cli.PrintJSON(cmd.OutOrStdout(), map[string]any{"revoked": true, "plugin_disabled": true})
+ }
+ var result map[string]any
+ if suffix == "/config" {
+ err = client.PutJSON(ctx, path, body, &result)
+ } else {
+ err = client.PostJSON(ctx, path, body, &result)
+ }
+ if err != nil {
+ return err
+ }
+ return cli.PrintJSON(cmd.OutOrStdout(), result)
+}
+
+func runPluginRemoteMCPConfigure(cmd *cobra.Command, args []string) error {
+ endpoint, _ := cmd.Flags().GetString("endpoint")
+ if endpoint == "" {
+ return fmt.Errorf("--endpoint is required")
+ }
+ credential, err := readRemoteMCPCredential(cmd)
+ if err != nil {
+ return err
+ }
+ publicConfig := json.RawMessage(`{}`)
+ if configPath, _ := cmd.Flags().GetString("public-config-file"); configPath != "" {
+ raw, err := os.ReadFile(filepath.Clean(configPath))
+ if err != nil {
+ return fmt.Errorf("read --public-config-file: %w", err)
+ }
+ publicConfig = raw
+ }
+ authType, _ := cmd.Flags().GetString("auth-type")
+ authHeader, _ := cmd.Flags().GetString("auth-header")
+ failurePolicy, _ := cmd.Flags().GetString("failure-policy")
+ return remoteMCPAPI(cmd, args, "/config", "configure", map[string]any{
+ "endpoint": endpoint, "public_config": publicConfig, "auth_type": authType,
+ "auth_header": authHeader, "credential": credential, "failure_policy": failurePolicy,
+ })
+}
+
+func runPluginRemoteMCPTest(cmd *cobra.Command, args []string) error {
+ return remoteMCPAPI(cmd, args, "/test", "test", map[string]any{})
+}
+
+func runPluginRemoteMCPApprove(cmd *cobra.Command, args []string) error {
+ tools, _ := cmd.Flags().GetStringSlice("tool")
+ if len(tools) == 0 {
+ return fmt.Errorf("at least one --tool is required")
+ }
+ return remoteMCPAPI(cmd, args, "/approve", "approve", map[string]any{"tools": tools})
+}
+
+func runPluginRemoteMCPRevoke(cmd *cobra.Command, args []string) error {
+ return remoteMCPAPI(cmd, args, "/credential", "revoke", nil)
+}
+
+func readRemoteMCPCredential(cmd *cobra.Command) (string, error) {
+ fromStdin, _ := cmd.Flags().GetBool("credential-stdin")
+ fromFile, _ := cmd.Flags().GetString("credential-file")
+ if fromStdin && fromFile != "" {
+ return "", fmt.Errorf("--credential-stdin and --credential-file are mutually exclusive")
+ }
+ if !fromStdin && fromFile == "" {
+ return "", nil
+ }
+ var raw []byte
+ var err error
+ if fromStdin {
+ raw, err = io.ReadAll(cmd.InOrStdin())
+ } else {
+ raw, err = os.ReadFile(filepath.Clean(fromFile))
+ }
+ if err != nil {
+ return "", fmt.Errorf("read Remote MCP credential: %w", err)
+ }
+ credential := strings.TrimSpace(string(raw))
+ if credential == "" {
+ return "", fmt.Errorf("Remote MCP credential input is empty")
+ }
+ return credential, nil
+}
diff --git a/server/cmd/multica/cmd_plugin_test.go b/server/cmd/multica/cmd_plugin_test.go
index 8d27e7b6cf..1da91cf7ab 100644
--- a/server/cmd/multica/cmd_plugin_test.go
+++ b/server/cmd/multica/cmd_plugin_test.go
@@ -78,3 +78,20 @@ func TestPluginInitRefusesNonEmptyDirectory(t *testing.T) {
t.Fatal("plugin init unexpectedly replaced a non-empty directory")
}
}
+
+func TestPluginInitRemoteMCPTemplate(t *testing.T) {
+ root := filepath.Join(t.TempDir(), "plugin")
+ cmd := pluginInitTestCommand(&bytes.Buffer{})
+ cmd.Flags().String("contribution", "remote-mcp", "")
+ cmd.Flags().String("endpoint-host", "tools.example.com", "")
+ if err := runPluginInit(cmd, []string{root}); err != nil {
+ t.Fatalf("plugin init remote-mcp: %v", err)
+ }
+ _, artifact, err := loadPluginSource(root)
+ if err != nil {
+ t.Fatalf("load remote-mcp template: %v", err)
+ }
+ if len(artifact.Manifest.Contributes.RemoteMCP) != 1 || len(artifact.Files) != 1 {
+ t.Fatalf("remote-mcp template = %+v", artifact.Manifest.Contributes)
+ }
+}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 8dc2ec10d2..ac1e958227 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -864,6 +864,21 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
slog.Info("vcs integration disabled (MULTICA_VCS_SECRET_KEY not set)")
}
+ // Remote MCP Plugin credentials use a dedicated deployment key. Keeping
+ // this separate from VCS and channel secrets gives operators an isolated
+ // rotation and blast radius; without it configuration endpoints fail closed.
+ if pluginKey, err := secretbox.LoadKey("MULTICA_PLUGIN_SECRET_KEY"); err == nil {
+ box, err := secretbox.New(pluginKey)
+ if err != nil {
+ slog.Error("plugins: secretbox.New failed; Remote MCP credentials disabled", "error", err)
+ } else if h.PluginService != nil {
+ h.PluginService.RemoteMCPSecrets = box
+ slog.Info("Remote MCP Plugin credential encryption enabled")
+ }
+ } else {
+ slog.Info("Remote MCP Plugin credentials disabled (MULTICA_PLUGIN_SECRET_KEY not set)")
+ }
+
if opts.HeartbeatScheduler != nil {
h.HeartbeatScheduler = opts.HeartbeatScheduler
}
@@ -1043,6 +1058,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Auth group made a missing cookie a hard 401, breaking the flow for exactly
// the browsers above; the other four composio endpoints stay session-gated.
r.Get("/api/integrations/composio/callback", h.ComposioCallback)
+ // Generic hosted Remote MCP OAuth callback. Identity and installation scope
+ // come exclusively from the encrypted, single-use state record.
+ r.With(authVerifyRL).Get("/api/plugins/remote-mcp/oauth/callback", h.CompletePluginRemoteMCPOAuth)
// Daemon API routes (require daemon token or valid user token)
r.Route("/api/daemon", func(r chi.Router) {
@@ -1071,6 +1089,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/runtimes/{runtimeId}/local-skills/import/{requestId}/result", h.ReportLocalSkillImportResult)
r.Get("/tasks/{taskId}/status", h.GetTaskStatus)
+ r.Get("/tasks/{taskId}/remote-mcp/{contributionId}/credential", h.ResolveTaskRemoteMCPCredential)
r.Post("/tasks/{taskId}/start", h.StartTask)
r.Post("/tasks/{taskId}/wait-local-directory", h.MarkTaskWaitingLocalDirectory)
r.Post("/tasks/{taskId}/progress", h.ReportTaskProgress)
@@ -1198,6 +1217,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/plugins/{installationId}/upgrade", h.UpgradePlugin)
r.Post("/plugins/{installationId}/enable", h.EnablePlugin)
r.Post("/plugins/{installationId}/disable", h.DisablePlugin)
+ r.Put("/plugins/{installationId}/remote-mcp/{contributionKey}/config", h.ConfigurePluginRemoteMCP)
+ r.Post("/plugins/{installationId}/remote-mcp/{contributionKey}/oauth/start", h.StartPluginRemoteMCPOAuth)
+ r.Post("/plugins/{installationId}/remote-mcp/{contributionKey}/test", h.TestPluginRemoteMCP)
+ r.Post("/plugins/{installationId}/remote-mcp/{contributionKey}/approve", h.ReviewPluginRemoteMCPTools)
+ r.Delete("/plugins/{installationId}/remote-mcp/{contributionKey}/credential", h.RevokePluginRemoteMCPCredential)
r.Post("/plugins/{installationId}/rollback", h.RollbackPlugin)
r.Delete("/plugins/{installationId}", h.UninstallPlugin)
})
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 9d60e3b872..74fcb8eb50 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -8,6 +8,7 @@ import (
"fmt"
"io"
"net/http"
+ "net/url"
"runtime"
"strings"
"sync"
@@ -190,6 +191,7 @@ func daemonClientCapabilities() string {
protocol.DaemonCapabilityCoalescedCommentsV1,
protocol.DaemonCapabilityExecutionManifestV1,
protocol.DaemonCapabilityAgentSkillV1,
+ protocol.DaemonCapabilityRemoteMCPV1,
protocol.DaemonCapabilityLocalWorktreeV1,
protocol.DaemonCapabilityRPCV1,
}, ",")
@@ -215,6 +217,22 @@ func (c *Client) ClaimTask(ctx context.Context, runtimeID string) (*Task, error)
return resp.Task, nil
}
+func (c *Client) ResolveRemoteMCPCredential(ctx context.Context, daemonToken, taskID, contributionID string) (http.Header, error) {
+ var response struct {
+ CredentialHeader 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))
+ if err := c.getJSONWithToken(ctx, path, daemonToken, &response); err != nil {
+ return nil, err
+ }
+ headers := make(http.Header)
+ if response.CredentialHeader != "" {
+ headers.Set(response.CredentialHeader, response.Credential)
+ }
+ return headers, nil
+}
+
// batchClaimRequestTimeout is the short, request-scoped deadline for the
// machine-level batch claim (MUL-4257). Unlike the per-runtime claim — which
// gets the full 30s control-plane timeout because a stall there only blocks
@@ -1045,12 +1063,19 @@ func (c *Client) postJSONVia(ctx context.Context, httpClient *http.Client, path
}
func (c *Client) getJSON(ctx context.Context, path string, respBody any) error {
+ return c.getJSONWithToken(ctx, path, c.token, respBody)
+}
+
+// getJSONWithToken performs one GET with an explicit credential. It is used by
+// the Remote MCP broker so its short-lived daemon token cannot replace or race
+// the client's long-lived PAT used by concurrent control-plane requests.
+func (c *Client) getJSONWithToken(ctx context.Context, path, token string, respBody any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil)
if err != nil {
return err
}
- if c.token != "" {
- req.Header.Set("Authorization", "Bearer "+c.token)
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
}
c.setIdentityHeaders(req)
diff --git a/server/internal/daemon/client_test.go b/server/internal/daemon/client_test.go
index 1dd5957212..68ea4d7919 100644
--- a/server/internal/daemon/client_test.go
+++ b/server/internal/daemon/client_test.go
@@ -86,6 +86,33 @@ func TestClient_IdentityHeaders_GetJSON(t *testing.T) {
}
}
+func TestClient_ResolveRemoteMCPCredentialUsesExplicitDaemonToken(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if got := r.Header.Get("Authorization"); got != "Bearer mdt_task_broker" {
+ t.Errorf("Authorization = %q, want short-lived daemon token", got)
+ }
+ if got := r.URL.Path; got != "/api/daemon/tasks/task-1/remote-mcp/contribution-1/credential" {
+ t.Errorf("path = %q", got)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"credential_header":"Authorization","credential":"Bearer upstream"}`))
+ }))
+ defer srv.Close()
+
+ c := NewClient(srv.URL)
+ c.SetToken("mul_owner_pat")
+ headers, err := c.ResolveRemoteMCPCredential(context.Background(), "mdt_task_broker", "task-1", "contribution-1")
+ if err != nil {
+ t.Fatalf("ResolveRemoteMCPCredential: %v", err)
+ }
+ if got := headers.Get("Authorization"); got != "Bearer upstream" {
+ t.Fatalf("resolved credential = %q", got)
+ }
+ if got := c.Token(); got != "mul_owner_pat" {
+ t.Fatalf("client PAT was mutated to %q", got)
+ }
+}
+
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.go
index 5b17b1586a..62d4043ff7 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -8,6 +8,7 @@ import (
"hash/fnv"
"log/slog"
"math/rand"
+ "net/http"
"os"
"os/exec"
"path/filepath"
@@ -6263,6 +6264,22 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
var agentMcpConfig json.RawMessage
var effectiveMcpConfig json.RawMessage
var cursorMcpAuthSource string
+ remoteMCPConfig, remoteMCPDiagnostics, remoteMCPBrokers, remoteMCPErr := startTaskRemoteMCPBrokers(
+ prepareCtx, ctx, task.ID, provider, task.RemoteMCPConnections,
+ func(resolveCtx context.Context, contributionID string) (http.Header, error) {
+ return d.client.ResolveRemoteMCPCredential(resolveCtx, task.RemoteMCPDaemonToken, task.ID, contributionID)
+ },
+ taskLog,
+ )
+ if remoteMCPErr != nil {
+ return TaskResult{}, fmt.Errorf("prepare Remote MCP broker: %w", remoteMCPErr)
+ }
+ if remoteMCPBrokers != nil {
+ defer remoteMCPBrokers.Close()
+ }
+ for _, diagnostic := range remoteMCPDiagnostics {
+ taskLog.Warn("Remote MCP degraded", "reason", diagnostic)
+ }
if task.Agent != nil {
agentMcpConfig = task.Agent.McpConfig
effectiveMcpConfig = agentMcpConfig
@@ -6274,6 +6291,13 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
} else {
effectiveMcpConfig = merged
}
+ if len(remoteMCPConfig) > 0 {
+ merged, mergeErr := mergeTaskRemoteMCPConfig(effectiveMcpConfig, remoteMCPConfig)
+ if mergeErr != nil {
+ return TaskResult{}, fmt.Errorf("merge Remote MCP broker configuration: %w", mergeErr)
+ }
+ effectiveMcpConfig = merged
+ }
if provider == "cursor" {
cursorMcpAuthSource = strings.TrimSpace(task.Agent.CustomEnv[execenv.CursorMcpAuthSourceEnv])
}
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 0589fcea72..3debf3a708 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -3053,7 +3053,7 @@ func TestShouldRetryWithFreshSession_UnresumableHistoryIsBackendAgnostic(t *test
}
}
-func TestExecuteAndDrain_CodexInactivityReportsToolResultTranscript(t *testing.T) {
+func TestExecuteAndDrain_CodexInactivityReportsMCPToolResultTranscript(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script fixture is POSIX-only")
}
@@ -3068,8 +3068,8 @@ func TestExecuteAndDrain_CodexInactivityReportsToolResultTranscript(t *testing.T
`read line` + "\n" +
`echo '{"jsonrpc":"2.0","id":3,"result":{}}'` + "\n" +
`echo '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-drain","turn":{"id":"turn-drain"}}}'` + "\n" +
- `echo '{"jsonrpc":"2.0","method":"item/started","params":{"threadId":"thr-drain","item":{"type":"commandExecution","id":"cmd-1","command":"git status"}}}'` + "\n" +
- `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-drain","item":{"type":"commandExecution","id":"cmd-1","aggregatedOutput":"clean"}}}'` + "\n" +
+ `echo '{"jsonrpc":"2.0","method":"item/started","params":{"threadId":"thr-drain","item":{"type":"mcpToolCall","id":"mcp-1","server":"plugin-exa-search","tool":"web_search_exa","arguments":{"query":"latest Multica news"},"status":"inProgress"}}}'` + "\n" +
+ `echo '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-drain","item":{"type":"mcpToolCall","id":"mcp-1","server":"plugin-exa-search","tool":"web_search_exa","arguments":{"query":"latest Multica news"},"status":"completed","durationMs":1627,"result":{"content":[{"type":"text","text":"private provider payload"}]}}}}'` + "\n" +
`sleep 5` + "\n"
if err := os.WriteFile(fakePath, []byte(script), 0o755); err != nil {
t.Fatalf("write fake codex: %v", err)
@@ -3124,10 +3124,11 @@ func TestExecuteAndDrain_CodexInactivityReportsToolResultTranscript(t *testing.T
mu.Lock()
var gotToolUse, gotToolResult bool
for _, msg := range reported {
- if msg.Seq == 1 && msg.Type == "tool_use" && msg.Tool == "exec_command" {
- gotToolUse = true
+ if msg.Seq == 1 && msg.Type == "tool_use" && msg.Tool == "web_search_exa" {
+ arguments, _ := msg.Input["arguments"].(map[string]any)
+ gotToolUse = msg.Input["server"] == "plugin-exa-search" && arguments["query"] == "latest Multica news"
}
- if msg.Seq == 2 && msg.Type == "tool_result" && msg.Tool == "exec_command" && msg.Output == "clean" {
+ if msg.Seq == 2 && msg.Type == "tool_result" && msg.Tool == "web_search_exa" && msg.Output == "completed\nduration: 1627 ms" {
gotToolResult = true
}
}
@@ -3138,7 +3139,7 @@ func TestExecuteAndDrain_CodexInactivityReportsToolResultTranscript(t *testing.T
if time.Now().After(deadline) {
mu.Lock()
defer mu.Unlock()
- t.Fatalf("expected tool_use seq=1 and tool_result seq=2 in transcript, got %+v", reported)
+ t.Fatalf("expected MCP tool_use seq=1 and tool_result seq=2 in transcript, got %+v", reported)
}
time.Sleep(10 * time.Millisecond)
}
diff --git a/server/internal/daemon/remote_mcp_broker.go b/server/internal/daemon/remote_mcp_broker.go
new file mode 100644
index 0000000000..22946d7051
--- /dev/null
+++ b/server/internal/daemon/remote_mcp_broker.go
@@ -0,0 +1,477 @@
+package daemon
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "net/url"
+ "sort"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+ "github.com/multica-ai/multica/server/pkg/pluginruntime"
+ "github.com/multica-ai/multica/server/pkg/remotemcp"
+)
+
+const (
+ remoteMCPMaxRequestBytes = 1 << 20
+ remoteMCPMaxCalls = 256
+ remoteMCPMaxConcurrency = 8
+)
+
+type remoteMCPBrokerSet struct {
+ servers []*http.Server
+ listeners []net.Listener
+ once sync.Once
+}
+
+type remoteMCPCredentialResolver func(context.Context, string) (http.Header, error)
+
+func (set *remoteMCPBrokerSet) Close() {
+ if set == nil {
+ return
+ }
+ set.once.Do(func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ for _, server := range set.servers {
+ _ = server.Shutdown(ctx)
+ }
+ for _, listener := range set.listeners {
+ _ = listener.Close()
+ }
+ })
+}
+
+func startTaskRemoteMCPBrokers(setupCtx, lifetimeCtx context.Context, taskID, provider string, connections []pluginruntime.RemoteMCPConnection, resolveCredential remoteMCPCredentialResolver, logger *slog.Logger) (json.RawMessage, []string, *remoteMCPBrokerSet, error) {
+ if len(connections) == 0 {
+ return nil, nil, nil, nil
+ }
+ set := &remoteMCPBrokerSet{}
+ servers := map[string]any{}
+ diagnostics := make([]string, 0)
+ for _, connection := range connections {
+ if !providerSupportsRemoteMCPBroker(provider) {
+ message := fmt.Sprintf("Remote MCP %s is incompatible with provider %s", connection.ContributionKey, provider)
+ if connection.FailurePolicy == "optional" {
+ diagnostics = append(diagnostics, message)
+ continue
+ }
+ set.Close()
+ return nil, diagnostics, nil, errors.New(message)
+ }
+ headers := make(http.Header)
+ if connection.CredentialHeader != "" && resolveCredential != nil {
+ resolvedHeaders, resolveErr := resolveCredential(setupCtx, connection.ContributionID)
+ if resolveErr != nil {
+ message := fmt.Sprintf("Remote MCP %s credential is unavailable", connection.ContributionKey)
+ if connection.FailurePolicy == "optional" {
+ diagnostics = append(diagnostics, message)
+ continue
+ }
+ set.Close()
+ return nil, diagnostics, nil, fmt.Errorf("%s: %w", message, resolveErr)
+ }
+ headers = resolvedHeaders
+ } else if connection.CredentialHeader != "" {
+ message := fmt.Sprintf("Remote MCP %s credential resolver is unavailable", connection.ContributionKey)
+ if connection.FailurePolicy == "optional" {
+ diagnostics = append(diagnostics, message)
+ continue
+ }
+ set.Close()
+ return nil, diagnostics, nil, errors.New(message)
+ }
+ discovered, _, err := remotemcp.Discover(setupCtx, connection.Endpoint, connection.EndpointAllowedHosts, connection.ProtocolVersions, headers)
+ if err == nil {
+ err = validatePinnedRemoteMCPTools(connection.ApprovedTools, discovered)
+ }
+ if err != nil {
+ message := fmt.Sprintf("Remote MCP %s failed startup validation", connection.ContributionKey)
+ if connection.FailurePolicy == "optional" {
+ diagnostics = append(diagnostics, message)
+ continue
+ }
+ set.Close()
+ return nil, diagnostics, nil, fmt.Errorf("%s: %w", message, err)
+ }
+ endpoint, err := remotemcp.ValidatePublicHTTPSEndpoint(setupCtx, connection.Endpoint, connection.EndpointAllowedHosts, nil)
+ if err != nil {
+ set.Close()
+ return nil, diagnostics, nil, err
+ }
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ set.Close()
+ return nil, diagnostics, nil, fmt.Errorf("listen for Remote MCP broker: %w", err)
+ }
+ pathToken, err := randomBrokerToken()
+ if err != nil {
+ _ = listener.Close()
+ set.Close()
+ return nil, diagnostics, nil, err
+ }
+ proxy := &remoteMCPProxy{
+ taskID: taskID, connection: connection, endpoint: endpoint,
+ client: remotemcp.NewSecureHTTPClient(endpoint), credentialHeaders: headers,
+ resolveCredential: resolveCredential, path: "/" + pathToken,
+ semaphore: make(chan struct{}, remoteMCPMaxConcurrency), logger: logger,
+ }
+ server := &http.Server{Handler: proxy, ReadHeaderTimeout: 5 * time.Second}
+ set.servers = append(set.servers, server)
+ set.listeners = append(set.listeners, listener)
+ go func() {
+ if serveErr := server.Serve(listener); serveErr != nil && !errors.Is(serveErr, http.ErrServerClosed) && logger != nil {
+ logger.Warn("Remote MCP broker stopped unexpectedly", "task_id", taskID, "contribution", connection.ContributionKey, "error", serveErr)
+ }
+ }()
+ name := remoteMCPServerName(connection)
+ servers[name] = map[string]any{
+ "type": "http",
+ "url": "http://" + listener.Addr().String() + proxy.path,
+ }
+ }
+ if len(servers) == 0 {
+ set.Close()
+ return nil, diagnostics, nil, nil
+ }
+ go func() {
+ <-lifetimeCtx.Done()
+ set.Close()
+ }()
+ raw, err := json.Marshal(map[string]any{"mcpServers": servers})
+ if err != nil {
+ set.Close()
+ return nil, diagnostics, nil, err
+ }
+ return raw, diagnostics, set, nil
+}
+
+func providerSupportsRemoteMCPBroker(provider string) bool {
+ switch provider {
+ case "codex", "claude", "hermes", "qoder":
+ return true
+ default:
+ return false
+ }
+}
+
+func validatePinnedRemoteMCPTools(approved, discovered []pluginruntime.RemoteMCPTool) error {
+ available := make(map[string]pluginruntime.RemoteMCPTool, len(discovered))
+ for _, tool := range discovered {
+ available[tool.Name] = tool
+ }
+ for _, pinned := range approved {
+ current, ok := available[pinned.Name]
+ if !ok {
+ return fmt.Errorf("approved tool %q is missing", pinned.Name)
+ }
+ if current.SchemaDigest != pinned.SchemaDigest {
+ return fmt.Errorf("approved tool %q schema drifted", pinned.Name)
+ }
+ }
+ return nil
+}
+
+func randomBrokerToken() (string, error) {
+ value := make([]byte, 24)
+ if _, err := rand.Read(value); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(value), nil
+}
+
+func remoteMCPServerName(connection pluginruntime.RemoteMCPConnection) string {
+ name := strings.Map(func(r rune) rune {
+ if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
+ return r
+ }
+ return '-'
+ }, strings.ToLower(connection.ContributionKey))
+ suffix := strings.ReplaceAll(connection.ContributionID, "-", "")
+ if len(suffix) > 8 {
+ suffix = suffix[:8]
+ }
+ return "plugin-" + name + "-" + suffix
+}
+
+type remoteMCPProxy struct {
+ taskID string
+ connection pluginruntime.RemoteMCPConnection
+ endpoint *url.URL
+ client *http.Client
+ credentialHeaders http.Header
+ resolveCredential remoteMCPCredentialResolver
+ path string
+ semaphore chan struct{}
+ calls atomic.Int64
+ logger *slog.Logger
+}
+
+type remoteMCPRequest struct {
+ JSONRPC string `json:"jsonrpc"`
+ ID json.RawMessage `json:"id,omitempty"`
+ Method string `json:"method"`
+ Params json.RawMessage `json:"params,omitempty"`
+}
+
+func (proxy *remoteMCPProxy) ServeHTTP(w http.ResponseWriter, request *http.Request) {
+ started := time.Now()
+ toolName := ""
+ resultClass := "rejected"
+ defer func() {
+ if proxy.logger != nil {
+ proxy.logger.Info("Remote MCP broker call",
+ "task_id", proxy.taskID,
+ "installation_id", proxy.connection.InstallationID,
+ "contribution", proxy.connection.ContributionKey,
+ "tool", toolName,
+ "duration_ms", time.Since(started).Milliseconds(),
+ "result_class", resultClass,
+ )
+ }
+ }()
+ if request.URL.Path != proxy.path || request.Method != http.MethodPost {
+ http.Error(w, "not found", http.StatusNotFound)
+ return
+ }
+ if proxy.calls.Add(1) > remoteMCPMaxCalls {
+ writeRemoteMCPError(w, nil, -32002, "Remote MCP task call limit exceeded")
+ return
+ }
+ select {
+ case proxy.semaphore <- struct{}{}:
+ defer func() { <-proxy.semaphore }()
+ default:
+ writeRemoteMCPError(w, nil, -32003, "Remote MCP concurrency limit exceeded")
+ return
+ }
+ raw, err := io.ReadAll(io.LimitReader(request.Body, remoteMCPMaxRequestBytes+1))
+ if err != nil || len(raw) > remoteMCPMaxRequestBytes {
+ writeRemoteMCPError(w, nil, -32600, "Remote MCP request is invalid")
+ return
+ }
+ var rpcRequest remoteMCPRequest
+ if err := json.Unmarshal(raw, &rpcRequest); err != nil || rpcRequest.JSONRPC != "2.0" {
+ writeRemoteMCPError(w, rpcRequest.ID, -32600, "Remote MCP request is invalid")
+ return
+ }
+ if !allowedRemoteMCPMethod(rpcRequest.Method) {
+ writeRemoteMCPError(w, rpcRequest.ID, -32601, "Only approved Remote MCP tools are available")
+ return
+ }
+ if rpcRequest.Method == "tools/call" {
+ var params struct {
+ Name string `json:"name"`
+ }
+ if err := json.Unmarshal(rpcRequest.Params, &params); err != nil || !proxy.toolApproved(params.Name) {
+ writeRemoteMCPError(w, rpcRequest.ID, -32602, "Remote MCP tool is not approved")
+ return
+ }
+ toolName = params.Name
+ }
+ upstream, err := http.NewRequestWithContext(request.Context(), http.MethodPost, proxy.endpoint.String(), bytes.NewReader(raw))
+ if err != nil {
+ writeRemoteMCPError(w, rpcRequest.ID, -32603, "Remote MCP request failed")
+ return
+ }
+ upstream.Header.Set("Content-Type", "application/json")
+ upstream.Header.Set("Accept", "application/json, text/event-stream")
+ for _, header := range []string{"Mcp-Session-Id", "Mcp-Protocol-Version", "Last-Event-ID"} {
+ if value := request.Header.Get(header); value != "" {
+ upstream.Header.Set(header, value)
+ }
+ }
+ credentialHeaders := proxy.credentialHeaders
+ if proxy.connection.CredentialHeader != "" && proxy.resolveCredential != nil {
+ credentialHeaders, err = proxy.resolveCredential(request.Context(), proxy.connection.ContributionID)
+ if err != nil {
+ resultClass = "credential_revoked"
+ writeRemoteMCPError(w, rpcRequest.ID, -32005, "Remote MCP credential is revoked or unavailable")
+ return
+ }
+ }
+ for key, values := range credentialHeaders {
+ for _, value := range values {
+ upstream.Header.Add(key, value)
+ }
+ }
+ response, err := proxy.client.Do(upstream)
+ if err != nil {
+ resultClass = "remote_error"
+ writeRemoteMCPError(w, rpcRequest.ID, -32000, "Remote MCP service is unavailable")
+ return
+ }
+ defer response.Body.Close()
+ responseBody, err := io.ReadAll(io.LimitReader(response.Body, remotemcp.MaxResponseBytes+1))
+ if err != nil || len(responseBody) > remotemcp.MaxResponseBytes {
+ resultClass = "remote_error"
+ writeRemoteMCPError(w, rpcRequest.ID, -32001, "Remote MCP response exceeded the allowed limit")
+ return
+ }
+ if response.StatusCode < 200 || response.StatusCode >= 300 {
+ resultClass = "remote_error"
+ writeRemoteMCPError(w, rpcRequest.ID, -32000, "Remote MCP service returned an error")
+ return
+ }
+ if rpcRequest.Method == "tools/list" {
+ responseBody, err = decodeRemoteMCPSSEData(response.Header.Get("Content-Type"), responseBody)
+ if err != nil {
+ resultClass = "remote_error"
+ writeRemoteMCPError(w, rpcRequest.ID, -32000, "Remote MCP service returned an invalid response")
+ return
+ }
+ responseBody, err = proxy.filterToolsListResponse(responseBody)
+ if err != nil {
+ resultClass = "schema_drift"
+ writeRemoteMCPError(w, rpcRequest.ID, -32004, "Remote MCP tool schema changed and requires review")
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ } else if contentType := response.Header.Get("Content-Type"); contentType != "" {
+ w.Header().Set("Content-Type", contentType)
+ }
+ for _, header := range []string{"Mcp-Session-Id", "Mcp-Protocol-Version"} {
+ if value := response.Header.Get(header); value != "" {
+ w.Header().Set(header, value)
+ }
+ }
+ w.WriteHeader(response.StatusCode)
+ _, _ = w.Write(responseBody)
+ resultClass = "success"
+}
+
+func decodeRemoteMCPSSEData(contentType string, raw []byte) ([]byte, error) {
+ if !strings.HasPrefix(strings.ToLower(contentType), "text/event-stream") {
+ return raw, nil
+ }
+ for _, line := range bytes.Split(raw, []byte("\n")) {
+ if bytes.HasPrefix(line, []byte("data:")) {
+ data := bytes.TrimSpace(bytes.TrimPrefix(line, []byte("data:")))
+ if len(data) > 0 {
+ return data, nil
+ }
+ }
+ }
+ return nil, errors.New("Remote MCP SSE response contained no data")
+}
+
+func allowedRemoteMCPMethod(method string) bool {
+ switch method {
+ case "initialize", "notifications/initialized", "notifications/cancelled", "ping", "tools/list", "tools/call":
+ return true
+ default:
+ return false
+ }
+}
+
+func (proxy *remoteMCPProxy) toolApproved(name string) bool {
+ for _, tool := range proxy.connection.ApprovedTools {
+ if tool.Name == name {
+ return true
+ }
+ }
+ return false
+}
+
+func (proxy *remoteMCPProxy) filterToolsListResponse(raw []byte) ([]byte, error) {
+ var response map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &response); err != nil {
+ return nil, err
+ }
+ var result map[string]json.RawMessage
+ if err := json.Unmarshal(response["result"], &result); err != nil {
+ return nil, err
+ }
+ var tools []struct {
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ InputSchema json.RawMessage `json:"inputSchema"`
+ }
+ if err := json.Unmarshal(result["tools"], &tools); err != nil {
+ return nil, err
+ }
+ byName := make(map[string]json.RawMessage, len(tools))
+ for _, tool := range tools {
+ canonical, err := canonicalRemoteMCPJSON(tool.InputSchema)
+ if err != nil {
+ return nil, err
+ }
+ byName[tool.Name] = canonical
+ }
+ pinned := append([]pluginruntime.RemoteMCPTool(nil), proxy.connection.ApprovedTools...)
+ sort.Slice(pinned, func(i, j int) bool { return pinned[i].Name < pinned[j].Name })
+ filtered := make([]map[string]any, 0, len(pinned))
+ for _, tool := range pinned {
+ current, ok := byName[tool.Name]
+ if !ok || plugincontract.DigestBytes(current) != tool.SchemaDigest {
+ return nil, errors.New("tool schema drift")
+ }
+ filtered = append(filtered, map[string]any{
+ "name": tool.Name, "description": tool.Description, "inputSchema": json.RawMessage(current),
+ })
+ }
+ result["tools"], _ = json.Marshal(filtered)
+ response["result"], _ = json.Marshal(result)
+ return json.Marshal(response)
+}
+
+func canonicalRemoteMCPJSON(raw json.RawMessage) (json.RawMessage, error) {
+ var value any
+ if err := json.Unmarshal(raw, &value); err != nil {
+ return nil, err
+ }
+ canonical, err := json.Marshal(value)
+ return json.RawMessage(canonical), err
+}
+
+func writeRemoteMCPError(w http.ResponseWriter, id json.RawMessage, code int, message string) {
+ if len(id) == 0 {
+ id = json.RawMessage("null")
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "jsonrpc": "2.0", "id": id,
+ "error": map[string]any{"code": code, "message": message},
+ })
+}
+
+func mergeTaskRemoteMCPConfig(base, overlay json.RawMessage) (json.RawMessage, error) {
+ if len(overlay) == 0 {
+ return base, nil
+ }
+ var overlayDocument struct {
+ MCPServers map[string]json.RawMessage `json:"mcpServers"`
+ }
+ if err := json.Unmarshal(overlay, &overlayDocument); err != nil {
+ return nil, err
+ }
+ baseDocument := struct {
+ MCPServers map[string]json.RawMessage `json:"mcpServers"`
+ }{MCPServers: map[string]json.RawMessage{}}
+ trimmed := bytes.TrimSpace(base)
+ if len(trimmed) > 0 && !bytes.Equal(trimmed, []byte("null")) {
+ if err := json.Unmarshal(trimmed, &baseDocument); err != nil {
+ return nil, err
+ }
+ if baseDocument.MCPServers == nil {
+ baseDocument.MCPServers = map[string]json.RawMessage{}
+ }
+ }
+ for name, server := range overlayDocument.MCPServers {
+ baseDocument.MCPServers[name] = server
+ }
+ return json.Marshal(baseDocument)
+}
diff --git a/server/internal/daemon/remote_mcp_broker_test.go b/server/internal/daemon/remote_mcp_broker_test.go
new file mode 100644
index 0000000000..e8c2d42bde
--- /dev/null
+++ b/server/internal/daemon/remote_mcp_broker_test.go
@@ -0,0 +1,167 @@
+package daemon
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+ "github.com/multica-ai/multica/server/pkg/pluginruntime"
+ "github.com/multica-ai/multica/server/pkg/remotemcp/remotemcptest"
+)
+
+func TestRemoteMCPProxyFiltersToolsAndInjectsCredential(t *testing.T) {
+ fixture := remotemcptest.NewServer()
+ defer fixture.Close()
+ schema := json.RawMessage(`{"type":"object","properties":{}}`)
+ canonical, err := canonicalRemoteMCPJSON(schema)
+ if err != nil {
+ t.Fatal(err)
+ }
+ endpoint, _ := url.Parse(fixture.URL)
+ proxy := &remoteMCPProxy{
+ taskID: "task", endpoint: endpoint, client: fixture.Client(), path: "/capability",
+ credentialHeaders: http.Header{"Authorization": []string{"Bearer " + remotemcptest.Credential}},
+ semaphore: make(chan struct{}, remoteMCPMaxConcurrency), logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ connection: pluginruntime.RemoteMCPConnection{
+ InstallationID: "installation", ContributionKey: "fixture",
+ ApprovedTools: []pluginruntime.RemoteMCPTool{{
+ Name: "fixture.read", Description: "pinned", InputSchema: canonical,
+ SchemaDigest: plugincontract.DigestBytes(canonical), Risk: "read",
+ }},
+ },
+ }
+
+ request := httptest.NewRequest(http.MethodPost, "/capability", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}`))
+ response := httptest.NewRecorder()
+ proxy.ServeHTTP(response, request)
+ if response.Code != http.StatusOK {
+ t.Fatalf("status = %d: %s", response.Code, response.Body.String())
+ }
+ if strings.Contains(response.Body.String(), "fixture.write") || !strings.Contains(response.Body.String(), "fixture.read") {
+ t.Fatalf("filtered tools/list = %s", response.Body.String())
+ }
+ if !strings.Contains(response.Body.String(), "pinned") {
+ t.Fatalf("tools/list did not preserve reviewed description: %s", response.Body.String())
+ }
+
+ writeSchema, err := canonicalRemoteMCPJSON(json.RawMessage(`{
+ "type":"object",
+ "required":["value"],
+ "properties":{"value":{"type":"string"}}
+ }`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ proxy.connection.ApprovedTools = append(proxy.connection.ApprovedTools, pluginruntime.RemoteMCPTool{
+ Name: "fixture.write", InputSchema: writeSchema, SchemaDigest: plugincontract.DigestBytes(writeSchema), Risk: "write",
+ })
+ writeRequest := httptest.NewRequest(http.MethodPost, "/capability", strings.NewReader(`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"fixture.write","arguments":{"value":"broker-write"}}}`))
+ writeResponse := httptest.NewRecorder()
+ proxy.ServeHTTP(writeResponse, writeRequest)
+ if writes := fixture.Writes(); len(writes) != 1 || writes[0] != "broker-write" {
+ t.Fatalf("fixture writes = %#v, response = %s", writes, writeResponse.Body.String())
+ }
+}
+
+func TestRemoteMCPProxyRejectsUnapprovedToolWithoutCallingUpstream(t *testing.T) {
+ called := false
+ upstream := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true }))
+ defer upstream.Close()
+ endpoint, _ := url.Parse(upstream.URL)
+ proxy := &remoteMCPProxy{
+ endpoint: endpoint, client: upstream.Client(), path: "/capability",
+ semaphore: make(chan struct{}, remoteMCPMaxConcurrency),
+ connection: pluginruntime.RemoteMCPConnection{ApprovedTools: []pluginruntime.RemoteMCPTool{{Name: "allowed"}}},
+ }
+ request := httptest.NewRequest(http.MethodPost, "/capability", bytes.NewBufferString(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"denied","arguments":{"secret":"not logged"}}}`))
+ response := httptest.NewRecorder()
+ proxy.ServeHTTP(response, request)
+ if called || !strings.Contains(response.Body.String(), "not approved") {
+ t.Fatalf("called=%v response=%s", called, response.Body.String())
+ }
+}
+
+func TestRemoteMCPProxyPreservesAcceptedNotificationStatus(t *testing.T) {
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
+ if request.Method != http.MethodPost {
+ t.Fatalf("upstream method = %s", request.Method)
+ }
+ w.WriteHeader(http.StatusAccepted)
+ }))
+ defer upstream.Close()
+ endpoint, _ := url.Parse(upstream.URL)
+ proxy := &remoteMCPProxy{
+ endpoint: endpoint, client: upstream.Client(), path: "/capability",
+ semaphore: make(chan struct{}, remoteMCPMaxConcurrency),
+ }
+
+ request := httptest.NewRequest(http.MethodPost, "/capability", bytes.NewBufferString(
+ `{"jsonrpc":"2.0","method":"notifications/initialized","params":{}}`,
+ ))
+ response := httptest.NewRecorder()
+ proxy.ServeHTTP(response, request)
+ if response.Code != http.StatusAccepted {
+ t.Fatalf("status = %d, want %d", response.Code, http.StatusAccepted)
+ }
+ if response.Body.Len() != 0 {
+ t.Fatalf("notification response body = %q, want empty", response.Body.String())
+ }
+}
+
+func TestRemoteMCPProxyRechecksCredentialBeforeUpstreamCall(t *testing.T) {
+ called := false
+ upstream := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true }))
+ defer upstream.Close()
+ endpoint, _ := url.Parse(upstream.URL)
+ proxy := &remoteMCPProxy{
+ endpoint: endpoint, client: upstream.Client(), path: "/capability",
+ semaphore: make(chan struct{}, remoteMCPMaxConcurrency),
+ connection: pluginruntime.RemoteMCPConnection{
+ ContributionID: "contribution", CredentialHeader: "Authorization",
+ ApprovedTools: []pluginruntime.RemoteMCPTool{{Name: "allowed"}},
+ },
+ resolveCredential: func(context.Context, string) (http.Header, error) {
+ return nil, errors.New("revoked")
+ },
+ }
+ request := httptest.NewRequest(http.MethodPost, "/capability", bytes.NewBufferString(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"allowed","arguments":{}}}`))
+ response := httptest.NewRecorder()
+ proxy.ServeHTTP(response, request)
+ if called || !strings.Contains(response.Body.String(), "revoked or unavailable") {
+ t.Fatalf("called=%v response=%s", called, response.Body.String())
+ }
+}
+
+func TestRemoteMCPProviderMatrixAndConfigMerge(t *testing.T) {
+ for _, provider := range []string{"codex", "claude", "hermes", "qoder"} {
+ if !providerSupportsRemoteMCPBroker(provider) {
+ t.Fatalf("provider %s must support Remote MCP", provider)
+ }
+ }
+ if providerSupportsRemoteMCPBroker("deveco") {
+ t.Fatal("unsupported provider was accepted")
+ }
+ merged, err := mergeTaskRemoteMCPConfig(
+ json.RawMessage(`{"mcpServers":{"agent":{"command":"agent"}}}`),
+ json.RawMessage(`{"mcpServers":{"plugin":{"type":"http","url":"http://127.0.0.1/mcp"}}}`),
+ )
+ if err != nil || !strings.Contains(string(merged), `"agent"`) || !strings.Contains(string(merged), `"plugin"`) {
+ t.Fatalf("merge = %s, %v", merged, err)
+ }
+}
+
+func TestDecodeRemoteMCPSSEData(t *testing.T) {
+ raw, err := decodeRemoteMCPSSEData("text/event-stream; charset=utf-8", []byte("event: message\ndata: {\"jsonrpc\":\"2.0\",\"id\":1}\n\n"))
+ if err != nil || string(raw) != `{"jsonrpc":"2.0","id":1}` {
+ t.Fatalf("decodeRemoteMCPSSEData = %q, %v", raw, err)
+ }
+}
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index ed20e13e0d..b2f9d80f2c 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"github.com/multica-ai/multica/server/internal/runtimeapps"
+ "github.com/multica-ai/multica/server/pkg/pluginruntime"
)
// AgentEntry describes a single available agent CLI.
@@ -70,12 +71,16 @@ type ActiveSiblingRunData struct {
// Task represents a claimed task from the server.
// Agent data (name, skills) is populated by the claim endpoint.
type Task struct {
- ID string `json:"id"`
- AgentID string `json:"agent_id"`
- RuntimeID string `json:"runtime_id"`
- IssueID string `json:"issue_id"`
- WorkspaceID string `json:"workspace_id"`
- PluginExecutionManifest *PluginExecutionManifestData `json:"plugin_execution_manifest,omitempty"`
+ ID string `json:"id"`
+ AgentID string `json:"agent_id"`
+ RuntimeID string `json:"runtime_id"`
+ IssueID string `json:"issue_id"`
+ WorkspaceID string `json:"workspace_id"`
+ PluginExecutionManifest *PluginExecutionManifestData `json:"plugin_execution_manifest,omitempty"`
+ RemoteMCPConnections []pluginruntime.RemoteMCPConnection `json:"remote_mcp_connections,omitempty"`
+ // 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"`
// 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`
@@ -172,6 +177,7 @@ type PluginExecutionManifestData struct {
ComposerVersion string `json:"composer_version"`
SchemaVersion int32 `json:"schema_version"`
OrderedContributions json.RawMessage `json:"ordered_contributions"`
+ Diagnostics []string `json:"diagnostics,omitempty"`
}
// ChatAttachmentMeta is the structured attachment metadata the daemon
diff --git a/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.go
index bf3795ac00..c9af98d736 100644
--- a/server/internal/featureflags/keys.go
+++ b/server/internal/featureflags/keys.go
@@ -23,9 +23,6 @@ const (
// gate pinned Task/Run execution: disabling discovery and management must not
// mutate an immutable execution manifest that is already in flight.
PluginsV1 = "plugins_v1"
- // PrivatePluginsV1 independently gates workspace-uploaded, unsigned Skill
- // Plugins. It is effective only while the base PluginsV1 contract is also on.
- PrivatePluginsV1 = "private_plugins_v1"
// agentBuilderCompat is no longer a release flag. Keep publishing the key
// as enabled so installed desktop clients that still gate the AI creation
// entry on this config decision receive the permanently enabled behavior.
@@ -47,7 +44,6 @@ var frontendPublicFlags = []string{
BillingWorkspaceSubscriptions,
ComposioMCPApps,
PluginsV1,
- PrivatePluginsV1,
}
func BillingWorkspaceSubscriptionsEnabled(ctx context.Context, flags *featureflag.Service) bool {
@@ -62,10 +58,6 @@ func PluginsV1Enabled(ctx context.Context, flags *featureflag.Service) bool {
return flags.IsEnabled(ctx, PluginsV1, false)
}
-func PrivatePluginsV1Enabled(ctx context.Context, flags *featureflag.Service) bool {
- return PluginsV1Enabled(ctx, flags) && flags.IsEnabled(ctx, PrivatePluginsV1, false)
-}
-
func EvaluateFrontendPublicFlags(ctx context.Context, flags *featureflag.Service) map[string]bool {
out := make(map[string]bool, len(frontendPublicFlags)+3)
for _, key := range frontendPublicFlags {
diff --git a/server/internal/featureflags/keys_test.go b/server/internal/featureflags/keys_test.go
index 5caa01b507..b718932f3d 100644
--- a/server/internal/featureflags/keys_test.go
+++ b/server/internal/featureflags/keys_test.go
@@ -3,8 +3,6 @@ package featureflags
import (
"context"
"testing"
-
- "github.com/multica-ai/multica/server/pkg/featureflag"
)
func TestResourceLabelsCompatDecisionStaysEnabled(t *testing.T) {
@@ -47,28 +45,11 @@ func TestPluginsV1DefaultsOff(t *testing.T) {
}
}
-func TestPrivatePluginsV1DefaultsOff(t *testing.T) {
+func TestPluginSubFlagsAreNotPublished(t *testing.T) {
flags := EvaluateFrontendPublicFlags(context.Background(), nil)
- if flags[PrivatePluginsV1] {
- t.Fatal("private_plugins_v1 must stay disabled unless explicitly enabled")
- }
-}
-
-func TestPrivatePluginsV1RequiresBothFlags(t *testing.T) {
- provider := featureflag.NewStaticProvider()
- flags := featureflag.NewService(provider)
- ctx := context.Background()
-
- provider.Set(PrivatePluginsV1, featureflag.Rule{Default: true})
- if PrivatePluginsV1Enabled(ctx, flags) {
- t.Fatal("private_plugins_v1 must stay off while plugins_v1 is off")
- }
- provider.Set(PluginsV1, featureflag.Rule{Default: true})
- if !PrivatePluginsV1Enabled(ctx, flags) {
- t.Fatal("private_plugins_v1 must be on when both flags are on")
- }
- provider.Set(PrivatePluginsV1, featureflag.Rule{Default: false})
- if PrivatePluginsV1Enabled(ctx, flags) {
- t.Fatal("private_plugins_v1 must stay off when its own flag is off")
+ for _, retired := range []string{"private_plugins_v1", "remote_mcp_plugins_v1"} {
+ if _, published := flags[retired]; published {
+ t.Fatalf("retired Plugin sub-flag %q must not be published", retired)
+ }
}
}
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 215133b191..7c6795c169 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -25,6 +25,7 @@ import (
"github.com/multica-ai/multica/server/internal/util"
"github.com/multica-ai/multica/server/pkg/agent"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/pluginruntime"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -314,6 +315,11 @@ type AgentTaskResponse struct {
IssueID string `json:"issue_id"`
WorkspaceID string `json:"workspace_id"`
PluginExecutionManifest *service.PluginExecutionManifestData `json:"plugin_execution_manifest,omitempty"`
+ RemoteMCPConnections []pluginruntime.RemoteMCPConnection `json:"remote_mcp_connections,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.
+ RemoteMCPDaemonToken string `json:"remote_mcp_daemon_token,omitempty"`
// WorkspaceContext is the workspace-level system prompt set in workspace
// settings (`workspace.context` DB column). Injected into the agent brief
// as `## Workspace Context` so every agent running in this workspace —
diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.go
index 77377834f6..773f694ff8 100644
--- a/server/internal/handler/config_test.go
+++ b/server/internal/handler/config_test.go
@@ -418,8 +418,10 @@ func TestGetConfigExposesFrontendFeatureFlags(t *testing.T) {
if cfg.FeatureFlags["plugins_v1"] {
t.Fatalf("plugins_v1: want false by default, got true")
}
- if cfg.FeatureFlags["private_plugins_v1"] {
- t.Fatalf("private_plugins_v1: want false by default, got true")
+ for _, retired := range []string{"private_plugins_v1", "remote_mcp_plugins_v1"} {
+ if _, published := cfg.FeatureFlags[retired]; published {
+ t.Fatalf("retired Plugin sub-flag %q must not be published", retired)
+ }
}
if !cfg.FeatureFlags["agents_skill_toggles"] {
t.Fatalf("agents_skill_toggles: want true for installed v0.4.0 clients, got false")
@@ -460,22 +462,3 @@ func TestGetConfigExposesEnabledPluginsV1Flag(t *testing.T) {
t.Fatal("plugins_v1: want true with flag enabled, got false")
}
}
-
-func TestGetConfigExposesEnabledPrivatePluginsV1Flag(t *testing.T) {
- h := &Handler{}
- withPrivatePluginsV1Flag(t, h, true, true)
-
- req := httptest.NewRequest(http.MethodGet, "/api/config", nil)
- w := httptest.NewRecorder()
- h.GetConfig(w, req)
- if w.Code != http.StatusOK {
- t.Fatalf("GetConfig enabled private_plugins_v1: expected 200, got %d: %s", w.Code, w.Body.String())
- }
- var cfg AppConfig
- if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {
- t.Fatalf("decode enabled config: %v", err)
- }
- if !cfg.FeatureFlags["plugins_v1"] || !cfg.FeatureFlags["private_plugins_v1"] {
- t.Fatalf("private Plugin flags not published together: %#v", cfg.FeatureFlags)
- }
-}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index d574db76bc..6f7324423a 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1720,6 +1720,16 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {
}
continue
}
+ remoteMCPToken, daemonTokens, derr := remoteMCPDaemonTokenForClaim(resp, rt)
+ if derr != nil {
+ slog.Error("batch claim: generate Remote MCP daemon token failed; requeueing claim",
+ "task_id", uuidToString(task.ID), "error", derr)
+ if _, rerr := h.TaskService.RequeueTaskAfterClaimFailure(r.Context(), task); rerr != nil {
+ slog.Error("batch claim: requeue after Remote MCP token failure failed",
+ "task_id", uuidToString(task.ID), "error", rerr)
+ }
+ continue
+ }
// Route through the SAME finalization as the per-runtime endpoint so the
// token and the comment-delivery receipt (delivered_comment_ids for
// comment/coalesced-comment tasks) are persisted atomically; on failure
@@ -1732,7 +1742,7 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {
WorkspaceID: parseUUID(resp.WorkspaceID),
UserID: rt.OwnerID,
ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(24 * time.Hour), Valid: true},
- }, deliveredCommentIDs, commentBackedTask)
+ }, deliveredCommentIDs, commentBackedTask, daemonTokens...)
if ferr != nil {
slog.Error("batch claim: finalize task claim failed; requeueing claim",
"task_id", uuidToString(task.ID), "error", ferr)
@@ -1743,6 +1753,7 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {
continue
}
resp.AuthToken = tokenStr
+ resp.RemoteMCPDaemonToken = remoteMCPToken
resp.DeliveredCommentIDs = uuidStringsOrEmpty(receipt)
out = append(out, resp)
}
@@ -1766,6 +1777,75 @@ type claimBuildFailure struct {
message string
}
+// remoteMCPDaemonTokenForClaim prepares the short-lived credential the daemon
+// uses to resolve write-only Remote MCP secrets for this task. The raw token is
+// returned only in the claim response; its hash is committed atomically with
+// the task-scoped agent token by FinalizeTaskClaim.
+func remoteMCPDaemonTokenForClaim(resp AgentTaskResponse, runtime db.AgentRuntime) (string, []db.CreateDaemonTokenParams, error) {
+ if len(resp.RemoteMCPConnections) == 0 {
+ return "", nil, nil
+ }
+ if !runtime.DaemonID.Valid || strings.TrimSpace(runtime.DaemonID.String) == "" {
+ return "", nil, errors.New("runtime daemon_id is required for Remote MCP")
+ }
+ raw, err := auth.GenerateDaemonToken()
+ if err != nil {
+ return "", nil, fmt.Errorf("generate Remote MCP daemon token: %w", err)
+ }
+ return raw, []db.CreateDaemonTokenParams{{
+ TokenHash: auth.HashToken(raw),
+ WorkspaceID: runtime.WorkspaceID,
+ DaemonID: runtime.DaemonID.String,
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(24 * time.Hour), Valid: true},
+ }}, nil
+}
+
+// failClaimedTaskBeforeLaunch settles a durable claim-time rejection before
+// the daemon ever receives the task. Leaving these failures in dispatched
+// makes the stale-claim reaper deliver the same impossible task forever and
+// leaves chat showing "starting" with no actionable outcome. If settlement
+// itself fails, release the exact claim so a later attempt can retry the gate.
+func (h *Handler) failClaimedTaskBeforeLaunch(
+ ctx context.Context,
+ task *db.AgentTaskQueue,
+ userMessage string,
+ failureReason taskfailure.Reason,
+ outcome string,
+ status int,
+ claimMessage string,
+) *claimBuildFailure {
+ if _, err := h.TaskService.FailTask(
+ ctx,
+ task.ID,
+ userMessage,
+ "",
+ "",
+ "",
+ failureReason.String(),
+ false,
+ "",
+ ); err != nil {
+ slog.Error("task claim: fail rejected task failed; requeueing claim",
+ "task_id", uuidToString(task.ID),
+ "outcome", outcome,
+ "error", err,
+ )
+ if _, requeueErr := h.TaskService.RequeueTaskAfterClaimFailure(ctx, *task); requeueErr != nil {
+ slog.Error("task claim: requeue after rejected-task settlement failure failed; stale reclaim will recover it",
+ "task_id", uuidToString(task.ID),
+ "outcome", outcome,
+ "error", requeueErr,
+ )
+ }
+ return &claimBuildFailure{
+ outcome: outcome + "_settle",
+ status: http.StatusInternalServerError,
+ message: "failed to settle a task rejected before launch",
+ }
+ }
+ return &claimBuildFailure{outcome: outcome, status: status, message: claimMessage}
+}
+
// buildClaimedTaskResponse assembles the full daemon claim payload for a
// single already-claimed task and computes the exact comment ids embedded in
// it (deliveredCommentIDs). Shared by the per-runtime handler
@@ -1795,13 +1875,69 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
_, pluginSkillRefs, pluginManifest, pluginErr := h.TaskService.LoadTaskPluginSkillBundles(r.Context(), task.ID)
if pluginErr != nil {
slog.Error("daemon claim: load pinned plugin contributions failed", "task_id", uuidToString(task.ID), "error", pluginErr)
- return resp, deliveredCommentIDs, 0, 0, &claimBuildFailure{status: http.StatusInternalServerError, message: "pinned plugin contributions are unavailable"}
+ failure := h.failClaimedTaskBeforeLaunch(
+ r.Context(),
+ task,
+ "This task could not start because its pinned Plugin contributions are unavailable. Retry the task; if it fails again, reinstall or re-enable the Plugin.",
+ taskfailure.ReasonSkillBundleUnavailable,
+ "error_plugin_contributions",
+ http.StatusInternalServerError,
+ "pinned plugin contributions are unavailable",
+ )
+ return resp, deliveredCommentIDs, 0, 0, failure
}
resp.PluginExecutionManifest = pluginManifest
+ remoteConnections, remoteDiagnostics, remoteErr := h.PluginService.ResolveTaskRemoteMCPConnections(r.Context(), task.ID)
+ if remoteErr != nil {
+ slog.Error("daemon claim: resolve pinned Remote MCP contribution failed", "task_id", uuidToString(task.ID), "error", remoteErr)
+ failure := h.failClaimedTaskBeforeLaunch(
+ r.Context(),
+ task,
+ "This task could not start because a required Remote MCP contribution is unavailable. Test the Plugin connection or update its configuration, then retry.",
+ taskfailure.ReasonAgentMissingConfig,
+ "error_required_remote_mcp",
+ http.StatusConflict,
+ "required Remote MCP contribution is unavailable",
+ )
+ return resp, deliveredCommentIDs, 0, 0, failure
+ }
+ if pluginManifest != nil && len(remoteDiagnostics) > 0 {
+ pluginManifest.Diagnostics = append(pluginManifest.Diagnostics, remoteDiagnostics...)
+ }
+ if len(remoteConnections) > 0 && !requestHasClientCapability(r, protocol.DaemonCapabilityRemoteMCPV1) {
+ for _, connection := range remoteConnections {
+ if connection.FailurePolicy == "required" {
+ failure := h.failClaimedTaskBeforeLaunch(
+ r.Context(),
+ task,
+ "This task could not start because its runtime does not support the required Remote MCP contribution. Update the runtime, then retry.",
+ taskfailure.ReasonAgentRuntimeVersionUnsupported,
+ "error_remote_mcp_runtime_incompatible",
+ http.StatusConflict,
+ "runtime does not support this task's required Remote MCP contribution",
+ )
+ return resp, deliveredCommentIDs, 0, 0, failure
+ }
+ }
+ if pluginManifest != nil {
+ pluginManifest.Diagnostics = append(pluginManifest.Diagnostics, "optional Remote MCP contributions omitted because the runtime is incompatible")
+ }
+ remoteConnections = nil
+ }
+ resp.RemoteMCPConnections = remoteConnections
if len(pluginSkillRefs) > 0 && (!requestHasClientCapability(r, protocol.DaemonCapabilitySkillBundlesV1) ||
!requestHasClientCapability(r, protocol.DaemonCapabilityExecutionManifestV1) ||
!requestHasClientCapability(r, protocol.DaemonCapabilityAgentSkillV1)) {
- return resp, deliveredCommentIDs, 0, 0, &claimBuildFailure{status: http.StatusConflict, message: "runtime does not support this task's plugin execution manifest"}
+ failure := h.failClaimedTaskBeforeLaunch(
+ r.Context(),
+ task,
+ "This task could not start because its runtime does not support the Plugin's Skill contribution. Update the runtime, then retry.",
+ taskfailure.ReasonAgentRuntimeVersionUnsupported,
+ "error_plugin_skill_runtime_incompatible",
+ http.StatusConflict,
+ "runtime does not support this task's plugin execution manifest",
+ )
+ return resp, deliveredCommentIDs, 0, 0, failure
}
if agent, err := h.Queries.GetAgent(r.Context(), task.AgentID); err == nil {
useSkillRefs := requestHasClientCapability(r, protocol.DaemonCapabilitySkillBundlesV1)
@@ -3025,6 +3161,15 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to mint task token")
return
}
+ remoteMCPToken, daemonTokens, derr := remoteMCPDaemonTokenForClaim(resp, runtime)
+ if derr != nil {
+ outcome = "error_remote_mcp_token"
+ slog.Error("task claim: failed to generate Remote MCP daemon token",
+ "task_id", uuidToString(task.ID), "error", derr)
+ requeueFailedClaim("remote_mcp_token_generation")
+ writeError(w, http.StatusInternalServerError, "failed to mint Remote MCP daemon token")
+ return
+ }
receipt, ferr := h.TaskService.FinalizeTaskClaim(r.Context(), *task, db.CreateTaskTokenParams{
TokenHash: auth.HashToken(tokenStr),
TaskID: task.ID,
@@ -3032,7 +3177,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
WorkspaceID: parseUUID(resp.WorkspaceID),
UserID: runtime.OwnerID,
ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(24 * time.Hour), Valid: true},
- }, deliveredCommentIDs, commentBackedTask)
+ }, deliveredCommentIDs, commentBackedTask, daemonTokens...)
if ferr != nil {
outcome = "error_claim_finalize"
slog.Error("task claim: failed to finalize token and comment delivery receipt",
@@ -3046,6 +3191,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
return
}
resp.AuthToken = tokenStr
+ resp.RemoteMCPDaemonToken = remoteMCPToken
task.DeliveredCommentIds = receipt
resp.DeliveredCommentIDs = uuidStringsOrEmpty(receipt)
diff --git a/server/internal/handler/daemon_batch_claim_test.go b/server/internal/handler/daemon_batch_claim_test.go
index 34c7636fb5..9900caf47a 100644
--- a/server/internal/handler/daemon_batch_claim_test.go
+++ b/server/internal/handler/daemon_batch_claim_test.go
@@ -7,6 +7,8 @@ import (
"net/http/httptest"
"strings"
"testing"
+
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
)
// batchClaimResponse mirrors the {"tasks":[...]} envelope ClaimTasksByRuntime
@@ -256,3 +258,59 @@ func TestClaimTasksByRuntime_CancelsTaskWhenRuntimeOwnerMissing(t *testing.T) {
t.Fatalf("task status = %s, want cancelled (owner missing)", status)
}
}
+
+// TestFailClaimedTaskBeforeLaunchSettlesDispatchedTask pins the claim-build
+// failure behavior used by required Plugin contributions. A durable rejection
+// must become a visible terminal task instead of remaining dispatched until
+// stale reclaim delivers the same impossible task again.
+func TestFailClaimedTaskBeforeLaunchSettlesDispatchedTask(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Prelaunch failure rt")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Prelaunch failure agent")
+ taskID := seedQueuedIssueTask(t, ctx, agentID, runtimeID, issueID)
+ if _, err := testPool.Exec(ctx, `
+ UPDATE agent_task_queue
+ SET status = 'dispatched', dispatched_at = now()
+ WHERE id = $1
+ `, taskID); err != nil {
+ t.Fatalf("dispatch task: %v", err)
+ }
+ task, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(taskID))
+ if err != nil {
+ t.Fatalf("load task: %v", err)
+ }
+
+ failure := testHandler.failClaimedTaskBeforeLaunch(
+ ctx,
+ &task,
+ "Required Remote MCP is unavailable. Test the Plugin connection, then retry.",
+ taskfailure.ReasonAgentMissingConfig,
+ "error_required_remote_mcp",
+ http.StatusConflict,
+ "required Remote MCP contribution is unavailable",
+ )
+ if failure == nil || failure.outcome != "error_required_remote_mcp" || failure.status != http.StatusConflict {
+ t.Fatalf("failure = %+v", failure)
+ }
+
+ var status, errorMessage, failureReason string
+ if err := testPool.QueryRow(ctx, `
+ SELECT status, error, failure_reason
+ FROM agent_task_queue
+ WHERE id = $1
+ `, taskID).Scan(&status, &errorMessage, &failureReason); err != nil {
+ t.Fatalf("read settled task: %v", err)
+ }
+ if status != "failed" {
+ t.Fatalf("task status = %q, want failed", status)
+ }
+ if errorMessage != "Required Remote MCP is unavailable. Test the Plugin connection, then retry." {
+ t.Fatalf("task error = %q", errorMessage)
+ }
+ if failureReason != taskfailure.ReasonAgentMissingConfig.String() {
+ t.Fatalf("failure_reason = %q", failureReason)
+ }
+}
diff --git a/server/internal/handler/daemon_comment_delivery_test.go b/server/internal/handler/daemon_comment_delivery_test.go
index eb8fc116ee..bb73a08bdb 100644
--- a/server/internal/handler/daemon_comment_delivery_test.go
+++ b/server/internal/handler/daemon_comment_delivery_test.go
@@ -908,6 +908,7 @@ func TestFinalizeTaskClaim_ReceiptCASFailureRollsBackInsertedToken(t *testing.T)
t.Fatalf("claim fixture task: task=%v err=%v", task, err)
}
tokenHash := "rolled-back-token-" + fixture.taskID
+ daemonTokenHash := "rolled-back-daemon-token-" + fixture.taskID
_, err = testHandler.TaskService.FinalizeTaskClaim(ctx, *task, db.CreateTaskTokenParams{
TokenHash: tokenHash,
TaskID: task.ID,
@@ -915,7 +916,12 @@ func TestFinalizeTaskClaim_ReceiptCASFailureRollsBackInsertedToken(t *testing.T)
WorkspaceID: parseUUID(testWorkspaceID),
UserID: parseUUID(testUserID),
ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true},
- }, []pgtype.UUID{parseUUID("00000000-0000-0000-0000-000000000099")}, true)
+ }, []pgtype.UUID{parseUUID("00000000-0000-0000-0000-000000000099")}, true, db.CreateDaemonTokenParams{
+ TokenHash: daemonTokenHash,
+ WorkspaceID: parseUUID(testWorkspaceID),
+ DaemonID: "daemon-claim-rollback",
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true},
+ })
if err == nil {
t.Fatalf("FinalizeTaskClaim accepted an out-of-plan receipt")
}
@@ -926,6 +932,13 @@ func TestFinalizeTaskClaim_ReceiptCASFailureRollsBackInsertedToken(t *testing.T)
if tokenCount != 0 {
t.Fatalf("receipt CAS failure committed %d generated token(s)", tokenCount)
}
+ var daemonTokenCount int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM daemon_token WHERE token_hash = $1`, daemonTokenHash).Scan(&daemonTokenCount); err != nil {
+ t.Fatalf("count rolled-back daemon token: %v", err)
+ }
+ if daemonTokenCount != 0 {
+ t.Fatalf("receipt CAS failure committed %d daemon token(s)", daemonTokenCount)
+ }
if got := deliveredCommentIDsForTask(t, fixture.taskID); len(got) != 0 {
t.Fatalf("receipt CAS failure advanced receipt: %v", got)
}
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index 4b26ff2d25..f5d51d2583 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -21,6 +21,7 @@ import (
"github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/pluginruntime"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -120,6 +121,32 @@ func newDaemonTokenRequest(method, path string, body any, workspaceID, daemonID
return req.WithContext(ctx)
}
+func TestRemoteMCPDaemonTokenForClaim(t *testing.T) {
+ runtime := db.AgentRuntime{
+ WorkspaceID: parseUUID(testWorkspaceID),
+ DaemonID: strToText("daemon-remote-mcp"),
+ }
+ raw, params, err := remoteMCPDaemonTokenForClaim(AgentTaskResponse{
+ RemoteMCPConnections: []pluginruntime.RemoteMCPConnection{{ContributionKey: "mobbin"}},
+ }, runtime)
+ if err != nil {
+ t.Fatalf("remoteMCPDaemonTokenForClaim: %v", err)
+ }
+ if !strings.HasPrefix(raw, "mdt_") {
+ t.Fatalf("raw token has unexpected prefix")
+ }
+ if len(params) != 1 || params[0].TokenHash != auth.HashToken(raw) {
+ t.Fatalf("daemon token params do not contain the generated token hash")
+ }
+ if params[0].WorkspaceID != runtime.WorkspaceID || params[0].DaemonID != "daemon-remote-mcp" {
+ t.Fatalf("daemon token scope = (%v, %q)", params[0].WorkspaceID, params[0].DaemonID)
+ }
+ remaining := time.Until(params[0].ExpiresAt.Time)
+ if remaining < 23*time.Hour || remaining > 24*time.Hour {
+ t.Fatalf("daemon token lifetime = %s, want about 24h", remaining)
+ }
+}
+
func TestListDaemonWorkspaces_UserScopedAndConditional(t *testing.T) {
w := httptest.NewRecorder()
req := newRequest(http.MethodGet, "/api/daemon/workspaces", nil)
diff --git a/server/internal/handler/featureflag_test.go b/server/internal/handler/featureflag_test.go
index cb73181b03..683f159849 100644
--- a/server/internal/handler/featureflag_test.go
+++ b/server/internal/handler/featureflag_test.go
@@ -15,17 +15,6 @@ func withPluginsV1Flag(t *testing.T, h *Handler, enabled bool) {
withFeatureFlag(t, h, featureflags.PluginsV1, enabled)
}
-func withPrivatePluginsV1Flag(t *testing.T, h *Handler, pluginsEnabled, privateEnabled bool) {
- t.Helper()
- provider := featureflag.NewStaticProvider()
- provider.Set(featureflags.PluginsV1, featureflag.Rule{Default: pluginsEnabled})
- provider.Set(featureflags.PrivatePluginsV1, featureflag.Rule{Default: privateEnabled})
- flags := featureflag.NewService(provider)
- original := h.FeatureFlags
- h.FeatureFlags = flags
- t.Cleanup(func() { h.FeatureFlags = original })
-}
-
func withFeatureFlag(t *testing.T, h *Handler, key string, enabled bool) {
t.Helper()
provider := featureflag.NewStaticProvider()
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index c0c5b5e3a1..2059379c97 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -83,9 +83,10 @@ type Config struct {
VCSIntegrationEnabled bool
// PublicURL is the absolute base URL the API is reachable at from the
// public internet, with no trailing slash (e.g. "https://multica.ai").
- // Used only to build webhook_url responses for autopilot webhook triggers
- // — never for auth, routing, or workspace resolution. Empty when unset,
- // in which case clients fall back to webhook_path + their own origin.
+ // Used to build webhook_url responses and the fixed Remote MCP OAuth
+ // callback URI — never to decide request identity, routing, or workspace
+ // scope. Empty when unset; webhook clients can fall back to their own origin,
+ // while OAuth Connect fails closed because providers require an exact URI.
// Reading the public host from request headers (Host / X-Forwarded-Host)
// is intentionally avoided so a misconfigured reverse proxy cannot trick
// the server into minting webhook URLs pointing at an attacker-controlled
diff --git a/server/internal/handler/plugin.go b/server/internal/handler/plugin.go
index 74e66c2b2a..25439e7a77 100644
--- a/server/internal/handler/plugin.go
+++ b/server/internal/handler/plugin.go
@@ -7,16 +7,20 @@ import (
"io"
"log/slog"
"net/http"
+ "net/url"
+ "strings"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/featureflags"
+ "github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/pluginbundled"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
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/pluginruntime"
)
func (h *Handler) pluginsV1Enabled(ctx context.Context) bool {
@@ -31,18 +35,6 @@ func (h *Handler) requirePluginsV1(w http.ResponseWriter, r *http.Request) bool
return false
}
-func (h *Handler) privatePluginsV1Enabled(ctx context.Context) bool {
- return featureflags.PrivatePluginsV1Enabled(ctx, h.FeatureFlags)
-}
-
-func (h *Handler) requirePrivatePluginsV1(w http.ResponseWriter, r *http.Request) bool {
- if h.privatePluginsV1Enabled(r.Context()) {
- return true
- }
- writeError(w, http.StatusServiceUnavailable, "Private Plugin management is not enabled")
- return false
-}
-
type pluginBindingResponse struct {
ScopeType string `json:"scope_type"`
ScopeID string `json:"scope_id"`
@@ -59,34 +51,64 @@ type pluginContributionResponse struct {
EntryDigest string `json:"entry_digest"`
}
+type pluginRemoteMCPConfigResponse struct {
+ ContributionKey string `json:"contribution_key"`
+ DefaultEndpoint string `json:"default_endpoint,omitempty"`
+ PreferredAuth string `json:"preferred_auth,omitempty"`
+ SupportedAuth []string `json:"supported_auth,omitempty"`
+ ConfigRevision int64 `json:"config_revision,omitempty"`
+ Endpoint string `json:"endpoint,omitempty"`
+ EndpointDomain string `json:"endpoint_domain,omitempty"`
+ AuthType string `json:"auth_type,omitempty"`
+ AuthHeader string `json:"auth_header,omitempty"`
+ PublicConfig json.RawMessage `json:"public_config,omitempty"`
+ ConnectionScope string `json:"connection_scope,omitempty"`
+ ConnectedBy string `json:"connected_by,omitempty"`
+ CredentialState string `json:"credential_state"`
+ CredentialHint string `json:"credential_hint,omitempty"`
+ FailurePolicy string `json:"failure_policy,omitempty"`
+ ApprovedTools []pluginruntime.RemoteMCPTool `json:"approved_tools"`
+ DiscoveredTools []pluginruntime.RemoteMCPTool `json:"discovered_tools"`
+ DiscoveredDigest string `json:"discovered_schema_digest,omitempty"`
+ SchemaDigest string `json:"schema_digest,omitempty"`
+ Reviewed bool `json:"reviewed"`
+ Ready bool `json:"ready"`
+}
+
+func remoteMCPConfigResponseReady(config pluginRemoteMCPConfigResponse) bool {
+ credentialReady := config.CredentialState == "configured" || config.CredentialState == "not_required"
+ return config.ConfigRevision > 0 && config.Reviewed && len(config.ApprovedTools) > 0 && config.SchemaDigest != "" && credentialReady
+}
+
type pluginInstallationResponse struct {
- ID string `json:"id"`
- PluginKey string `json:"plugin_key"`
- DisplayName string `json:"display_name"`
- DesiredVersion string `json:"desired_version"`
- ActiveVersion string `json:"active_version,omitempty"`
- Enabled bool `json:"enabled"`
- DesiredGeneration int64 `json:"desired_generation"`
- ActiveGeneration int64 `json:"active_generation"`
- LifecycleStatus string `json:"lifecycle_status"`
- HealthState string `json:"health_state,omitempty"`
- HealthReason string `json:"health_reason,omitempty"`
- Description string `json:"description,omitempty"`
- Publisher string `json:"publisher"`
- PublisherType string `json:"publisher_type"`
- TrustTier string `json:"trust_tier"`
- SourceKind string `json:"source_kind"`
- SourceRef string `json:"source_ref"`
- UploaderID string `json:"uploader_id,omitempty"`
- ManifestDigest string `json:"manifest_digest"`
- ArchiveDigest string `json:"archive_digest"`
- ArtifactDigest string `json:"artifact_digest"`
- SignatureVerified bool `json:"signature_verified"`
- RequestedCaps []string `json:"requested_capabilities"`
- AvailableVersions []string `json:"available_versions"`
- Contributions []string `json:"contributions"`
- ContributionInfo []pluginContributionResponse `json:"contribution_details"`
- Bindings []pluginBindingResponse `json:"bindings"`
+ ID string `json:"id"`
+ PluginKey string `json:"plugin_key"`
+ DisplayName string `json:"display_name"`
+ DesiredVersion string `json:"desired_version"`
+ ActiveVersion string `json:"active_version,omitempty"`
+ Enabled bool `json:"enabled"`
+ DesiredGeneration int64 `json:"desired_generation"`
+ ActiveGeneration int64 `json:"active_generation"`
+ LifecycleStatus string `json:"lifecycle_status"`
+ HealthState string `json:"health_state,omitempty"`
+ HealthReason string `json:"health_reason,omitempty"`
+ Description string `json:"description,omitempty"`
+ Publisher string `json:"publisher"`
+ PublisherType string `json:"publisher_type"`
+ TrustTier string `json:"trust_tier"`
+ SourceKind string `json:"source_kind"`
+ SourceRef string `json:"source_ref"`
+ UploaderID string `json:"uploader_id,omitempty"`
+ ManifestDigest string `json:"manifest_digest"`
+ ArchiveDigest string `json:"archive_digest"`
+ ArtifactDigest string `json:"artifact_digest"`
+ SignatureVerified bool `json:"signature_verified"`
+ RequestedCaps []string `json:"requested_capabilities"`
+ AvailableVersions []string `json:"available_versions"`
+ Contributions []string `json:"contributions"`
+ ContributionInfo []pluginContributionResponse `json:"contribution_details"`
+ Bindings []pluginBindingResponse `json:"bindings"`
+ RemoteMCP []pluginRemoteMCPConfigResponse `json:"remote_mcp"`
}
func (h *Handler) pluginInstallationResponse(r *http.Request, installation db.PluginInstallation, health *db.PluginHealth) (pluginInstallationResponse, error) {
@@ -131,6 +153,7 @@ func (h *Handler) pluginInstallationResponseWithReleases(r *http.Request, instal
Contributions: []string{},
ContributionInfo: []pluginContributionResponse{},
Bindings: []pluginBindingResponse{},
+ RemoteMCP: []pluginRemoteMCPConfigResponse{},
}
var releases []db.PluginRelease
if prefetchedReleases != nil {
@@ -158,6 +181,64 @@ func (h *Handler) pluginInstallationResponseWithReleases(r *http.Request, instal
EntryPath: contribution.EntryPath,
EntryDigest: contribution.EntryDigest,
})
+ if contribution.Type == plugincontract.ContributionRemoteMCPV1 {
+ remote := pluginRemoteMCPConfigResponse{
+ ContributionKey: contribution.ContributionKey,
+ CredentialState: "missing",
+ ApprovedTools: []pluginruntime.RemoteMCPTool{},
+ DiscoveredTools: []pluginruntime.RemoteMCPTool{},
+ }
+ for _, declaration := range manifest.Contributes.RemoteMCP {
+ if declaration.Key == contribution.ContributionKey {
+ remote.DefaultEndpoint = declaration.EndpointPolicy.DefaultEndpoint
+ remote.PreferredAuth = declaration.Authentication.Preferred
+ remote.SupportedAuth = append([]string(nil), declaration.Authentication.Supported...)
+ break
+ }
+ }
+ config, configErr := h.Queries.GetLatestPluginInstallationConfig(r.Context(), db.GetLatestPluginInstallationConfigParams{
+ WorkspaceID: installation.WorkspaceID, InstallationID: installation.ID, ContributionID: contribution.ID,
+ })
+ if configErr == nil {
+ remote.ConfigRevision = config.Revision
+ remote.Endpoint = config.Endpoint
+ remote.AuthType = config.AuthType
+ remote.AuthHeader = config.AuthHeader
+ remote.PublicConfig = append(json.RawMessage(nil), config.PublicConfig...)
+ remote.FailurePolicy = config.FailurePolicy
+ remote.SchemaDigest = config.SchemaDigest.String
+ remote.DiscoveredDigest = config.DiscoveredSchemaDigest.String
+ remote.Reviewed = config.ReviewedAt.Valid
+ if endpoint, parseErr := url.Parse(config.Endpoint); parseErr == nil {
+ remote.EndpointDomain = endpoint.Hostname()
+ }
+ _ = json.Unmarshal(config.ApprovedTools, &remote.ApprovedTools)
+ _ = json.Unmarshal(config.DiscoveredTools, &remote.DiscoveredTools)
+ if config.AuthType == "none" {
+ remote.CredentialState = "not_required"
+ } else if config.SecretRef.Valid {
+ secret, secretErr := h.Queries.GetActivePluginRemoteMCPSecret(r.Context(), db.GetActivePluginRemoteMCPSecretParams{
+ ID: config.SecretRef, WorkspaceID: installation.WorkspaceID,
+ InstallationID: installation.ID, ContributionID: contribution.ID,
+ })
+ if secretErr == nil {
+ remote.CredentialState = "configured"
+ remote.CredentialHint = secret.Hint
+ remote.ConnectedBy = uuidToString(secret.CreatedBy)
+ // V1 execution configs are workspace-pinned. Recording the
+ // connecting user now keeps the wire contract ready for a
+ // future per-user connection selector without exposing tokens.
+ remote.ConnectionScope = "workspace"
+ } else if errors.Is(secretErr, pgx.ErrNoRows) {
+ remote.CredentialState = "revoked"
+ }
+ }
+ } else if !errors.Is(configErr, pgx.ErrNoRows) {
+ return pluginInstallationResponse{}, configErr
+ }
+ remote.Ready = remoteMCPConfigResponseReady(remote)
+ response.RemoteMCP = append(response.RemoteMCP, remote)
+ }
}
bindings, err := h.Queries.ListLatestPluginBindings(r.Context(), installation.ID)
if err != nil {
@@ -202,7 +283,7 @@ func (h *Handler) ListPlugins(w http.ResponseWriter, r *http.Request) {
}
func (h *Handler) ListPrivatePlugins(w http.ResponseWriter, r *http.Request) {
- if !h.requirePrivatePluginsV1(w, r) {
+ if !h.requirePluginsV1(w, r) {
return
}
workspaceID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")
@@ -218,7 +299,7 @@ func (h *Handler) ListPrivatePlugins(w http.ResponseWriter, r *http.Request) {
}
func (h *Handler) GetPrivatePluginStatus(w http.ResponseWriter, r *http.Request) {
- if !h.requirePrivatePluginsV1(w, r) {
+ if !h.requirePluginsV1(w, r) {
return
}
workspaceID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")
@@ -457,7 +538,7 @@ func (h *Handler) InstallPlugin(w http.ResponseWriter, r *http.Request) {
}
func (h *Handler) InstallPrivatePlugin(w http.ResponseWriter, r *http.Request) {
- if !h.requirePrivatePluginsV1(w, r) {
+ if !h.requirePluginsV1(w, r) {
return
}
workspaceID, actorID, ok := pluginRequestIDs(w, r)
@@ -483,6 +564,10 @@ func (h *Handler) InstallPrivatePlugin(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "Private Plugin package exceeds the package limit")
return
}
+ if _, validateErr := plugincontract.ValidateArtifact(archive); validateErr != nil {
+ writeError(w, http.StatusBadRequest, "Private Plugin package is invalid")
+ return
+ }
installation, err := h.PluginService.InstallPrivateArchive(r.Context(), workspaceID, actorID, archive)
if err != nil {
writePluginError(w, r, err)
@@ -508,7 +593,7 @@ func (h *Handler) UpgradePlugin(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if !h.requirePluginInstallationFeature(w, r, workspaceID, installationID, false) {
+ if !h.requirePluginInstallation(w, r, workspaceID, installationID) {
return
}
var request pluginReleaseRequest
@@ -557,7 +642,7 @@ func (h *Handler) setPluginEnabled(w http.ResponseWriter, r *http.Request, enabl
if !ok {
return
}
- if !h.requirePluginInstallationFeature(w, r, workspaceID, installationID, !enabled) {
+ if !h.requirePluginInstallation(w, r, workspaceID, installationID) {
return
}
request := pluginBindingRequest{ScopeType: "workspace", ScopeID: uuidToString(workspaceID)}
@@ -605,7 +690,7 @@ func (h *Handler) RollbackPlugin(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if !h.requirePluginInstallationFeature(w, r, workspaceID, installationID, false) {
+ if !h.requirePluginInstallation(w, r, workspaceID, installationID) {
return
}
var request struct {
@@ -640,7 +725,7 @@ func (h *Handler) UninstallPlugin(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if !h.requirePluginInstallationFeature(w, r, workspaceID, installationID, true) {
+ if !h.requirePluginInstallation(w, r, workspaceID, installationID) {
return
}
if err := h.PluginService.UninstallPlugin(r.Context(), workspaceID, installationID, actorID); err != nil {
@@ -650,15 +735,260 @@ func (h *Handler) UninstallPlugin(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
-func (h *Handler) requirePluginInstallationFeature(w http.ResponseWriter, r *http.Request, workspaceID, installationID pgtype.UUID, allowPrivateTeardown bool) bool {
+type remoteMCPConfigRequest struct {
+ Endpoint string `json:"endpoint"`
+ PublicConfig json.RawMessage `json:"public_config"`
+ AuthType string `json:"auth_type"`
+ AuthHeader string `json:"auth_header"`
+ Credential string `json:"credential"`
+ FailurePolicy string `json:"failure_policy"`
+}
+
+type remoteMCPOAuthStartRequest struct {
+ Endpoint string `json:"endpoint"`
+ PublicConfig json.RawMessage `json:"public_config"`
+ FailurePolicy string `json:"failure_policy"`
+ Scope string `json:"scope"`
+ ClientID string `json:"client_id"`
+ ClientSecret string `json:"client_secret"`
+ TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
+ AuthorizationEndpoint string `json:"authorization_endpoint"`
+ TokenEndpoint string `json:"token_endpoint"`
+ ReturnTo string `json:"return_to"`
+}
+
+const remoteMCPOAuthCallbackPath = "/api/plugins/remote-mcp/oauth/callback"
+
+func (h *Handler) StartPluginRemoteMCPOAuth(w http.ResponseWriter, r *http.Request) {
+ workspaceID, actorID, installationID, ok := h.remoteMCPRequestIDs(w, r)
+ if !ok {
+ return
+ }
+ var request remoteMCPOAuthStartRequest
+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ callbackBase := strings.TrimRight(h.cfg.PublicURL, "/")
+ if callbackBase == "" {
+ writeError(w, http.StatusServiceUnavailable, "MULTICA_PUBLIC_URL is required for Remote MCP OAuth")
+ return
+ }
+ result, err := h.PluginService.BeginRemoteMCPOAuth(r.Context(), workspaceID, installationID, actorID, chi.URLParam(r, "contributionKey"), service.RemoteMCPOAuthStartInput{
+ Endpoint: request.Endpoint, PublicConfig: request.PublicConfig, FailurePolicy: request.FailurePolicy,
+ Scope: request.Scope, ClientID: request.ClientID, ClientSecret: request.ClientSecret,
+ TokenEndpointAuthMethod: request.TokenEndpointAuthMethod,
+ AuthorizationEndpoint: request.AuthorizationEndpoint, TokenEndpoint: request.TokenEndpoint,
+ RedirectURI: callbackBase + remoteMCPOAuthCallbackPath, ReturnTo: request.ReturnTo,
+ })
+ if err != nil {
+ writePluginError(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]string{"authorization_url": result.AuthorizationURL})
+}
+
+// CompletePluginRemoteMCPOAuth is intentionally public. The single-use,
+// short-lived state hash carries the installation and actor identity; browser
+// cookies are neither required nor trusted on this cross-site callback.
+func (h *Handler) CompletePluginRemoteMCPOAuth(w http.ResponseWriter, r *http.Request) {
+ if !h.requirePluginsV1(w, r) {
+ return
+ }
+ result, err := h.PluginService.CompleteRemoteMCPOAuth(r.Context(), r.URL.Query().Get("state"), r.URL.Query().Get("code"))
+ if err != nil {
+ providerError := strings.TrimSpace(r.URL.Query().Get("error"))
+ if len(providerError) > 128 {
+ providerError = providerError[:128]
+ }
+ errorKind := "internal"
+ errorMessage := "Remote MCP OAuth callback failed"
+ var pluginErr *service.PluginError
+ if errors.As(err, &pluginErr) {
+ errorKind = string(pluginErr.Kind)
+ errorMessage = pluginErr.Message
+ }
+ slog.Warn("Remote MCP OAuth callback failed",
+ "error_kind", errorKind,
+ "error_message", errorMessage,
+ "provider_error", providerError,
+ "has_state", r.URL.Query().Get("state") != "",
+ "has_code", r.URL.Query().Get("code") != "",
+ )
+ }
+ returnTo := result.ReturnTo
+ if returnTo == "" {
+ returnTo = "/"
+ }
+ parsed, parseErr := url.Parse(returnTo)
+ if parseErr != nil || parsed.IsAbs() || parsed.Host != "" || !strings.HasPrefix(parsed.Path, "/") || strings.HasPrefix(parsed.Path, "//") {
+ parsed = &url.URL{Path: "/"}
+ }
+ query := parsed.Query()
+ if err == nil {
+ query.Set("remote_mcp_connected", "1")
+ } else {
+ query.Set("remote_mcp_error", "connect_failed")
+ }
+ parsed.RawQuery = query.Encode()
+ destination := parsed.String()
+ if appURL := resolveFrontendAppURL(); appURL != "" {
+ destination = strings.TrimRight(appURL, "/") + destination
+ }
+ http.Redirect(w, r, destination, http.StatusFound)
+}
+
+func (h *Handler) ConfigurePluginRemoteMCP(w http.ResponseWriter, r *http.Request) {
+ workspaceID, actorID, installationID, ok := h.remoteMCPRequestIDs(w, r)
+ if !ok {
+ return
+ }
+ var request remoteMCPConfigRequest
+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil || request.Endpoint == "" {
+ writeError(w, http.StatusBadRequest, "endpoint is required")
+ return
+ }
+ result, err := h.PluginService.ConfigureRemoteMCP(r.Context(), workspaceID, installationID, actorID, chi.URLParam(r, "contributionKey"), service.RemoteMCPConfigInput{
+ Endpoint: request.Endpoint, PublicConfig: request.PublicConfig, AuthType: request.AuthType,
+ AuthHeader: request.AuthHeader, Credential: request.Credential, FailurePolicy: request.FailurePolicy,
+ })
+ if err != nil {
+ writePluginError(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "config_revision": result.Config.Revision,
+ "credential_state": credentialState(result.Config),
+ "reviewed": false,
+ "discovered_tools": result.DiscoveredTools,
+ "discovered_schema_digest": result.SchemaDigest,
+ })
+}
+
+func (h *Handler) TestPluginRemoteMCP(w http.ResponseWriter, r *http.Request) {
+ workspaceID, _, installationID, ok := h.remoteMCPRequestIDs(w, r)
+ if !ok {
+ return
+ }
+ result, err := h.PluginService.TestRemoteMCP(r.Context(), workspaceID, installationID, chi.URLParam(r, "contributionKey"))
+ if err != nil {
+ writePluginError(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "ok": true, "config_revision": result.Config.Revision,
+ "discovered_tools": result.DiscoveredTools, "discovered_schema_digest": result.SchemaDigest,
+ })
+}
+
+func (h *Handler) ReviewPluginRemoteMCPTools(w http.ResponseWriter, r *http.Request) {
+ workspaceID, actorID, installationID, ok := h.remoteMCPRequestIDs(w, r)
+ if !ok {
+ return
+ }
+ var request struct {
+ Tools []string `json:"tools"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
+ writeError(w, http.StatusBadRequest, "tools are required")
+ return
+ }
+ result, err := h.PluginService.ReviewRemoteMCPTools(r.Context(), workspaceID, installationID, actorID, chi.URLParam(r, "contributionKey"), request.Tools)
+ if err != nil {
+ writePluginError(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "config_revision": result.Config.Revision, "reviewed": true,
+ "approved_tools": request.Tools, "schema_digest": result.SchemaDigest,
+ })
+}
+
+func (h *Handler) RevokePluginRemoteMCPCredential(w http.ResponseWriter, r *http.Request) {
+ workspaceID, actorID, installationID, ok := h.remoteMCPRequestIDs(w, r)
+ if !ok {
+ return
+ }
+ if err := h.PluginService.RevokeRemoteMCPCredential(r.Context(), workspaceID, installationID, actorID, chi.URLParam(r, "contributionKey")); err != nil {
+ writePluginError(w, r, err)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// ResolveTaskRemoteMCPCredential is daemon-only and intentionally returns
+// write-only credential material. Management APIs and provider configuration
+// never call this route. Every request re-checks the active scoped secret so
+// revocation takes effect for running brokers before their next upstream call.
+func (h *Handler) ResolveTaskRemoteMCPCredential(w http.ResponseWriter, r *http.Request) {
+ // DaemonAuth also accepts user PATs/JWTs for legacy daemon routes. This
+ // endpoint returns secret material, so it deliberately requires the
+ // workspace-scoped daemon-token path instead of that compatibility fallback.
+ if middleware.DaemonAuthPathFromContext(r.Context()) != middleware.DaemonAuthPathDaemonToken {
+ writeError(w, http.StatusForbidden, "daemon token required")
+ return
+ }
+ task, ok := h.requireDaemonTaskAccess(w, r, chi.URLParam(r, "taskId"))
+ if !ok {
+ return
+ }
+ // A daemon token is workspace scoped, but the credential belongs to the
+ // concrete machine executing this task. Do not let another daemon in the
+ // same workspace use its own token to resolve this task's secret.
+ runtime, err := h.Queries.GetAgentRuntime(r.Context(), task.RuntimeID)
+ if err != nil {
+ if !isNotFound(err) {
+ slog.Warn("load Remote MCP task runtime failed", "task_id", uuidToString(task.ID), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to load task runtime")
+ return
+ }
+ writeError(w, http.StatusNotFound, "task not found")
+ return
+ }
+ if !runtime.DaemonID.Valid || runtime.DaemonID.String != middleware.DaemonIDFromContext(r.Context()) {
+ writeError(w, http.StatusNotFound, "task not found")
+ return
+ }
+ header, credential, err := h.PluginService.ResolveTaskRemoteMCPCredential(r.Context(), task.ID, chi.URLParam(r, "contributionId"))
+ if err != nil {
+ writePluginError(w, r, err)
+ return
+ }
+ w.Header().Set("Cache-Control", "no-store")
+ writeJSON(w, http.StatusOK, map[string]string{"credential_header": header, "credential": credential})
+}
+
+func (h *Handler) remoteMCPRequestIDs(w http.ResponseWriter, r *http.Request) (pgtype.UUID, pgtype.UUID, pgtype.UUID, bool) {
+ if !h.requirePluginsV1(w, r) {
+ return pgtype.UUID{}, pgtype.UUID{}, pgtype.UUID{}, false
+ }
+ workspaceID, actorID, ok := pluginRequestIDs(w, r)
+ if !ok {
+ return pgtype.UUID{}, pgtype.UUID{}, pgtype.UUID{}, false
+ }
+ installationID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "installationId"), "installation_id")
+ if !ok {
+ return pgtype.UUID{}, pgtype.UUID{}, pgtype.UUID{}, false
+ }
+ if !h.requirePluginInstallation(w, r, workspaceID, installationID) {
+ return pgtype.UUID{}, pgtype.UUID{}, pgtype.UUID{}, false
+ }
+ return workspaceID, actorID, installationID, true
+}
+
+func credentialState(config db.PluginInstallationConfig) string {
+ if config.AuthType == "none" {
+ return "not_required"
+ }
+ return "configured"
+}
+
+func (h *Handler) requirePluginInstallation(w http.ResponseWriter, r *http.Request, workspaceID, installationID pgtype.UUID) bool {
installation, err := h.Queries.GetPluginInstallation(r.Context(), installationID)
if err != nil || installation.WorkspaceID != workspaceID || installation.UninstalledAt.Valid {
writeError(w, http.StatusNotFound, "Plugin installation not found")
return false
}
- if installation.SourceKind == plugincontract.SourcePrivateDev && !allowPrivateTeardown && !h.requirePrivatePluginsV1(w, r) {
- return false
- }
return true
}
diff --git a/server/internal/handler/plugin_test.go b/server/internal/handler/plugin_test.go
index 3a717dd70b..1784e86ac7 100644
--- a/server/internal/handler/plugin_test.go
+++ b/server/internal/handler/plugin_test.go
@@ -17,6 +17,7 @@ import (
"github.com/multica-ai/multica/server/internal/testutil/plugintest"
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/pluginruntime"
)
type failPluginDetailQueryDB struct {
@@ -61,6 +62,31 @@ func pluginHandlerRequest(method, path string, body []byte, params map[string]st
return request.WithContext(context.WithValue(request.Context(), chi.RouteCtxKey, routeContext))
}
+func TestRemoteMCPConfigResponseReady(t *testing.T) {
+ ready := pluginRemoteMCPConfigResponse{
+ ConfigRevision: 1, CredentialState: "configured", Reviewed: true,
+ ApprovedTools: []pluginruntime.RemoteMCPTool{{Name: "search"}}, SchemaDigest: "sha256:test",
+ }
+ if !remoteMCPConfigResponseReady(ready) {
+ t.Fatal("complete Remote MCP configuration was not ready")
+ }
+ for name, edit := range map[string]func(*pluginRemoteMCPConfigResponse){
+ "missing config": func(config *pluginRemoteMCPConfigResponse) { config.ConfigRevision = 0 },
+ "missing credential": func(config *pluginRemoteMCPConfigResponse) { config.CredentialState = "missing" },
+ "unreviewed": func(config *pluginRemoteMCPConfigResponse) { config.Reviewed = false },
+ "no approved tools": func(config *pluginRemoteMCPConfigResponse) { config.ApprovedTools = nil },
+ "missing digest": func(config *pluginRemoteMCPConfigResponse) { config.SchemaDigest = "" },
+ } {
+ t.Run(name, func(t *testing.T) {
+ config := ready
+ edit(&config)
+ if remoteMCPConfigResponseReady(config) {
+ t.Fatal("incomplete Remote MCP configuration was ready")
+ }
+ })
+ }
+}
+
func TestPluginHTTPLifecycleForInstalledReferenceRelease(t *testing.T) {
withPluginsV1Flag(t, testHandler, true)
cleanup := func() {
@@ -225,18 +251,24 @@ func TestPluginManagementUnavailableWhenFlagDisabled(t *testing.T) {
}
for name, handler := range map[string]http.HandlerFunc{
- "list installed": h.ListPlugins,
- "list catalog": h.ListPluginCatalog,
- "catalog detail": h.GetPluginCatalogRelease,
- "install": h.InstallPlugin,
- "upgrade": h.UpgradePlugin,
- "enable": h.EnablePlugin,
- "disable": h.DisablePlugin,
- "rollback": h.RollbackPlugin,
- "private list": h.ListPrivatePlugins,
- "private status": h.GetPrivatePluginStatus,
- "private install": h.InstallPrivatePlugin,
- "uninstall": h.UninstallPlugin,
+ "list installed": h.ListPlugins,
+ "list catalog": h.ListPluginCatalog,
+ "catalog detail": h.GetPluginCatalogRelease,
+ "install": h.InstallPlugin,
+ "upgrade": h.UpgradePlugin,
+ "enable": h.EnablePlugin,
+ "disable": h.DisablePlugin,
+ "rollback": h.RollbackPlugin,
+ "private list": h.ListPrivatePlugins,
+ "private status": h.GetPrivatePluginStatus,
+ "private install": h.InstallPrivatePlugin,
+ "uninstall": h.UninstallPlugin,
+ "remote oauth start": h.StartPluginRemoteMCPOAuth,
+ "remote oauth callback": h.CompletePluginRemoteMCPOAuth,
+ "remote configure": h.ConfigurePluginRemoteMCP,
+ "remote test": h.TestPluginRemoteMCP,
+ "remote review": h.ReviewPluginRemoteMCPTools,
+ "remote revoke": h.RevokePluginRemoteMCPCredential,
} {
t.Run(name, func(t *testing.T) {
recorder := httptest.NewRecorder()
@@ -251,36 +283,26 @@ func TestPluginManagementUnavailableWhenFlagDisabled(t *testing.T) {
}
}
-func TestPrivatePluginManagementRequiresBothFlags(t *testing.T) {
- for _, flags := range []struct {
- name string
- plugins, privatePlugin bool
- }{
- {name: "base off", plugins: false, privatePlugin: true},
- {name: "private off", plugins: true, privatePlugin: false},
+func TestPrivatePluginManagementRequiresPluginsV1(t *testing.T) {
+ h := &Handler{}
+ withPluginsV1Flag(t, h, false)
+ for name, handler := range map[string]http.HandlerFunc{
+ "list": h.ListPrivatePlugins,
+ "status": h.GetPrivatePluginStatus,
+ "install": h.InstallPrivatePlugin,
} {
- t.Run(flags.name, func(t *testing.T) {
- h := &Handler{}
- withPrivatePluginsV1Flag(t, h, flags.plugins, flags.privatePlugin)
- for name, handler := range map[string]http.HandlerFunc{
- "list": h.ListPrivatePlugins,
- "status": h.GetPrivatePluginStatus,
- "install": h.InstallPrivatePlugin,
- } {
- t.Run(name, func(t *testing.T) {
- recorder := httptest.NewRecorder()
- handler(recorder, pluginHandlerRequest(http.MethodGet, "/plugins/private", nil, map[string]string{"id": testWorkspaceID}))
- if recorder.Code != http.StatusServiceUnavailable {
- t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
- }
- })
+ t.Run(name, func(t *testing.T) {
+ recorder := httptest.NewRecorder()
+ handler(recorder, pluginHandlerRequest(http.MethodGet, "/plugins/private", nil, map[string]string{"id": testWorkspaceID}))
+ if recorder.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
})
}
}
func TestPrivatePluginHTTPUploadListAndUninstall(t *testing.T) {
- withPrivatePluginsV1Flag(t, testHandler, true, true)
+ withPluginsV1Flag(t, testHandler, true)
cleanup := func() {
ctx := context.Background()
testPool.Exec(ctx, `DELETE FROM plugin_health WHERE workspace_id = $1`, testWorkspaceID)
@@ -346,23 +368,31 @@ func TestPrivatePluginHTTPUploadListAndUninstall(t *testing.T) {
t.Fatalf("private enable status=%d body=%s", recorder.Code, recorder.Body.String())
}
- withPrivatePluginsV1Flag(t, testHandler, true, false)
+ withPluginsV1Flag(t, testHandler, false)
recorder = httptest.NewRecorder()
testHandler.ListPlugins(recorder, pluginHandlerRequest(http.MethodGet, "/plugins", nil, map[string]string{"id": testWorkspaceID}))
- if recorder.Code != http.StatusOK || !bytes.Contains(recorder.Body.Bytes(), []byte("dev.multica.incident-triage")) {
- t.Fatalf("private Plugin must remain visible for teardown when flag is off: status=%d body=%s", recorder.Code, recorder.Body.String())
+ if recorder.Code != http.StatusServiceUnavailable {
+ t.Fatalf("Plugin list with plugins_v1 off status=%d body=%s", recorder.Code, recorder.Body.String())
}
recorder = httptest.NewRecorder()
testHandler.EnablePlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/enable", nil, params))
if recorder.Code != http.StatusServiceUnavailable {
- t.Fatalf("private enable with flag off status=%d body=%s", recorder.Code, recorder.Body.String())
+ t.Fatalf("Plugin enable with plugins_v1 off status=%d body=%s", recorder.Code, recorder.Body.String())
}
recorder = httptest.NewRecorder()
testHandler.DisablePlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/disable", nil, params))
- if recorder.Code != http.StatusOK {
- t.Fatalf("private disable with flag off status=%d body=%s", recorder.Code, recorder.Body.String())
+ if recorder.Code != http.StatusServiceUnavailable {
+ t.Fatalf("Plugin disable with plugins_v1 off status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+ recorder = httptest.NewRecorder()
+ testHandler.UninstallPlugin(recorder, pluginHandlerRequest(http.MethodDelete, "/plugins/"+installed.ID, nil, map[string]string{
+ "id": testWorkspaceID, "installationId": installed.ID,
+ }))
+ if recorder.Code != http.StatusServiceUnavailable {
+ t.Fatalf("Plugin uninstall with plugins_v1 off status=%d body=%s", recorder.Code, recorder.Body.String())
}
+ withPluginsV1Flag(t, testHandler, true)
recorder = httptest.NewRecorder()
testHandler.UninstallPlugin(recorder, pluginHandlerRequest(http.MethodDelete, "/plugins/"+installed.ID, nil, map[string]string{
"id": testWorkspaceID, "installationId": installed.ID,
@@ -370,7 +400,6 @@ func TestPrivatePluginHTTPUploadListAndUninstall(t *testing.T) {
if recorder.Code != http.StatusNoContent {
t.Fatalf("private uninstall status=%d body=%s", recorder.Code, recorder.Body.String())
}
- withPrivatePluginsV1Flag(t, testHandler, true, true)
recorder = httptest.NewRecorder()
testHandler.GetPrivatePluginStatus(recorder, pluginHandlerRequest(http.MethodGet, "/plugins/private/dev.multica.incident-triage", nil, map[string]string{
"id": testWorkspaceID, "pluginRef": "dev.multica.incident-triage",
@@ -379,3 +408,39 @@ func TestPrivatePluginHTTPUploadListAndUninstall(t *testing.T) {
t.Fatalf("uninstalled private status=%d body=%s", recorder.Code, recorder.Body.String())
}
}
+
+func TestResolveTaskRemoteMCPCredentialRejectsNonDaemonAuth(t *testing.T) {
+ h := &Handler{}
+ recorder := httptest.NewRecorder()
+ request := pluginHandlerRequest(http.MethodGet, "/api/daemon/tasks/task-id/remote-mcp/contribution-id/credential", nil, map[string]string{
+ "taskId": "task-id",
+ "contributionId": "contribution-id",
+ })
+
+ h.ResolveTaskRemoteMCPCredential(recorder, request)
+
+ if recorder.Code != http.StatusForbidden {
+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+}
+
+func TestResolveTaskRemoteMCPCredentialRejectsDifferentDaemonInWorkspace(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fixture := createCommentDeliveryFixture(t, "Remote MCP daemon isolation")
+ request := newDaemonTokenRequest(http.MethodGet,
+ "/api/daemon/tasks/"+fixture.taskID+"/remote-mcp/contribution-id/credential",
+ nil, testWorkspaceID, "different-daemon")
+ routeCtx := chi.NewRouteContext()
+ routeCtx.URLParams.Add("taskId", fixture.taskID)
+ routeCtx.URLParams.Add("contributionId", "contribution-id")
+ request = request.WithContext(context.WithValue(request.Context(), chi.RouteCtxKey, routeCtx))
+
+ recorder := httptest.NewRecorder()
+ testHandler.ResolveTaskRemoteMCPCredential(recorder, request)
+
+ if recorder.Code != http.StatusNotFound {
+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+}
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 4953031e63..d6160946c3 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -93,7 +93,10 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"plugin_grant": workspaceDelete,
"plugin_health": workspaceDelete,
"plugin_identity": workspaceDeleteKeep,
+ "plugin_installation_config": workspaceDelete,
"plugin_installation": workspaceDelete,
+ "plugin_remote_mcp_oauth_state": workspaceDelete,
+ "plugin_remote_mcp_secret": workspaceDelete,
"plugin_release": workspaceDeleteKeep,
"plugin_workspace_capability_state": workspaceDelete,
"project": workspaceDelete,
diff --git a/server/internal/pluginbundled/catalog.go b/server/internal/pluginbundled/catalog.go
index 591abe3a12..38ec92dd6c 100644
--- a/server/internal/pluginbundled/catalog.go
+++ b/server/internal/pluginbundled/catalog.go
@@ -278,6 +278,7 @@ func CompatibleWithV1Host(manifest plugincontract.Manifest) (bool, string) {
supported := map[string]bool{
plugincontract.DaemonFeatureExecutionManifestV1: true,
plugincontract.DaemonFeatureAgentSkillV1: true,
+ plugincontract.DaemonFeatureRemoteMCPV1: true,
}
for _, feature := range manifest.Compatibility.RequiredDaemonFeatures {
if !supported[feature] {
diff --git a/server/internal/pluginbundled/catalog_test.go b/server/internal/pluginbundled/catalog_test.go
index c868e52ad7..bd137ada2e 100644
--- a/server/internal/pluginbundled/catalog_test.go
+++ b/server/internal/pluginbundled/catalog_test.go
@@ -4,8 +4,23 @@ import (
"io/fs"
"testing"
"testing/fstest"
+
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
)
+func TestV1HostSupportsRemoteMCPDaemonFeature(t *testing.T) {
+ manifest := plugincontract.Manifest{Compatibility: plugincontract.Compatibility{
+ HostAPI: ">=1.0.0 <2.0.0",
+ RequiredDaemonFeatures: []string{
+ plugincontract.DaemonFeatureExecutionManifestV1,
+ plugincontract.DaemonFeatureRemoteMCPV1,
+ },
+ }}
+ if compatible, why := CompatibleWithV1Host(manifest); !compatible {
+ t.Fatalf("Remote MCP V1 compatibility = false, %s", why)
+ }
+}
+
func TestBundledCatalogLoadsSignedOfficialReleases(t *testing.T) {
catalog := Load()
if diagnostics := catalog.Diagnostics(); len(diagnostics) != 0 {
diff --git a/server/internal/service/plugin.go b/server/internal/service/plugin.go
index a44464064a..0d8e832e5b 100644
--- a/server/internal/service/plugin.go
+++ b/server/internal/service/plugin.go
@@ -15,12 +15,15 @@ import (
"github.com/multica-ai/multica/server/pkg/plugincontract"
"github.com/multica-ai/multica/server/pkg/pluginruntime"
"github.com/multica-ai/multica/server/pkg/skillbundle"
+ "golang.org/x/sync/singleflight"
)
type PluginService struct {
- Queries *db.Queries
- TxStarter TxStarter
- BundledCatalog *pluginbundled.Catalog
+ Queries *db.Queries
+ TxStarter TxStarter
+ BundledCatalog *pluginbundled.Catalog
+ RemoteMCPSecrets RemoteMCPSecretBox
+ remoteMCPOAuthRefresh singleflight.Group
}
const (
@@ -212,6 +215,7 @@ func (s *PluginService) InstallPluginRelease(ctx context.Context, workspaceID, a
return db.PluginInstallation{}, newPluginError(PluginErrorConflict, "Plugin is already installed", nil)
}
auditAction := "plugin_private_uploaded"
+ needsReconcile := false
if existing.DesiredReleaseID != release.ID {
currentRelease, currentErr := q.GetPluginRelease(ctx, existing.DesiredReleaseID)
if currentErr != nil {
@@ -230,10 +234,32 @@ func (s *PluginService) InstallPluginRelease(ctx context.Context, workspaceID, a
if err != nil {
return db.PluginInstallation{}, fmt.Errorf("update private Plugin release: %w", err)
}
+ needsReconcile = true
+ auditAction = "plugin_private_upgraded"
+ }
+ // Private Plugin uploads are the capability-approval surface: a fresh
+ // install grants every requested capability below. Keep upgrades
+ // consistent by granting capabilities newly introduced by the release.
+ // Existing denied grants remain denied; an upload must not silently
+ // override an explicit revocation. This also repairs installations made
+ // by older servers that activated the contribution metadata but omitted
+ // its new grant, leaving the Skill visible in status yet absent at run
+ // time.
+ grantsChanged, err := grantMissingPrivatePluginCapabilities(
+ ctx,
+ q,
+ workspaceID,
+ existing.ID,
+ actorID,
+ publication.Release.Manifest.RequestedCapabilities,
+ )
+ if err != nil {
+ return db.PluginInstallation{}, err
+ }
+ if needsReconcile || grantsChanged {
if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {
return db.PluginInstallation{}, err
}
- auditAction = "plugin_private_upgraded"
}
if err := createPluginAudit(ctx, q, workspaceID, actorID, auditAction, identity, release, existing); err != nil {
return db.PluginInstallation{}, err
@@ -281,6 +307,41 @@ func (s *PluginService) InstallPluginRelease(ctx context.Context, workspaceID, a
return s.Queries.GetPluginInstallation(ctx, installation.ID)
}
+func grantMissingPrivatePluginCapabilities(
+ ctx context.Context,
+ q *db.Queries,
+ workspaceID, installationID, actorID pgtype.UUID,
+ requested []string,
+) (bool, error) {
+ latest, err := q.ListLatestPluginGrants(ctx, installationID)
+ if err != nil {
+ return false, fmt.Errorf("list private Plugin grants: %w", err)
+ }
+ existing := make(map[string]struct{}, len(latest))
+ for _, grant := range latest {
+ existing[grant.Capability] = struct{}{}
+ }
+ changed := false
+ for _, capability := range requested {
+ if _, ok := existing[capability]; ok {
+ continue
+ }
+ if _, err := q.CreatePluginGrantRevision(ctx, db.CreatePluginGrantRevisionParams{
+ Capability: capability,
+ Decision: "granted",
+ Limits: []byte(`{}`),
+ ApprovedBy: actorID,
+ InstallationID: installationID,
+ WorkspaceID: workspaceID,
+ }); err != nil {
+ return false, fmt.Errorf("grant upgraded private Plugin capability %s: %w", capability, err)
+ }
+ existing[capability] = struct{}{}
+ changed = true
+ }
+ return changed, nil
+}
+
func ensurePluginRelease(ctx context.Context, q *db.Queries, workspaceID pgtype.UUID, publication PluginReleasePublication) (db.PluginIdentity, db.PluginRelease, error) {
releaseData := publication.Release
manifest := releaseData.Manifest
@@ -480,6 +541,11 @@ func (s *PluginService) setPluginBinding(ctx context.Context, workspaceID, insta
if err != nil {
return db.PluginInstallation{}, err
}
+ if enabled {
+ if err := validateRemoteMCPInstallationReady(ctx, q, workspaceID, installation, release); err != nil {
+ return db.PluginInstallation{}, err
+ }
+ }
if scopeType == "workspace" && scopeID != workspaceID {
return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin binding target not found", nil)
}
@@ -537,6 +603,47 @@ func (s *PluginService) setPluginBinding(ctx context.Context, workspaceID, insta
return s.Queries.GetPluginInstallation(ctx, installationID)
}
+func validateRemoteMCPInstallationReady(ctx context.Context, q *db.Queries, workspaceID pgtype.UUID, installation db.PluginInstallation, release db.PluginRelease) error {
+ contributions, err := q.ListPluginContributionsByRelease(ctx, release.ID)
+ if err != nil {
+ return err
+ }
+ configs, err := q.ListLatestPluginInstallationConfigs(ctx, db.ListLatestPluginInstallationConfigsParams{
+ WorkspaceID: workspaceID, InstallationID: installation.ID,
+ })
+ if err != nil {
+ return err
+ }
+ byContribution := make(map[string]db.PluginInstallationConfig, len(configs))
+ for _, config := range configs {
+ byContribution[util.UUIDToString(config.ContributionID)] = config
+ }
+ for _, contribution := range contributions {
+ if contribution.Type != plugincontract.ContributionRemoteMCPV1 {
+ continue
+ }
+ config, ok := byContribution[util.UUIDToString(contribution.ID)]
+ var approved []pluginruntime.RemoteMCPTool
+ if ok {
+ _ = json.Unmarshal(config.ApprovedTools, &approved)
+ }
+ if !ok || !config.ReviewedAt.Valid || len(approved) == 0 || !config.SchemaDigest.Valid {
+ return newPluginError(PluginErrorConflict, "Remote MCP configuration and tool review must be complete before enabling", nil)
+ }
+ if config.AuthType != "none" {
+ if !config.SecretRef.Valid {
+ return newPluginError(PluginErrorConflict, "Remote MCP credential must be configured before enabling", nil)
+ }
+ if _, err := q.GetActivePluginRemoteMCPSecret(ctx, db.GetActivePluginRemoteMCPSecretParams{
+ ID: config.SecretRef, WorkspaceID: workspaceID, InstallationID: installation.ID, ContributionID: contribution.ID,
+ }); err != nil {
+ return newPluginError(PluginErrorConflict, "Remote MCP credential must be configured before enabling", nil)
+ }
+ }
+ }
+ return nil
+}
+
func (s *PluginService) RollbackPlugin(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, version string) (db.PluginInstallation, error) {
tx, err := s.TxStarter.Begin(ctx)
if err != nil {
@@ -684,6 +791,7 @@ func (s *PluginService) reconcileWorkspaceTx(ctx context.Context, q *db.Queries,
})
entries := make([]pluginruntime.CompiledEntry, 0, len(rows))
+ releaseFiles := make(map[string][]db.PluginArtifactFile)
for _, key := range keys {
contributionRows := grouped[key]
row := contributionRows[0]
@@ -694,13 +802,6 @@ func (s *PluginService) reconcileWorkspaceTx(ctx context.Context, q *db.Queries,
if err := json.Unmarshal(row.RequiredDaemonFeatures, &features); err != nil {
return db.PluginCapabilitySnapshot{}, fmt.Errorf("decode daemon features: %w", err)
}
- bundleManifest := skillbundle.BuildManifest(skillbundle.Skill{
- ID: "plugin:" + util.UUIDToString(row.ContributionID),
- Source: skillbundle.SourcePlugin,
- Name: row.ContributionKey,
- Description: row.Description,
- Content: row.EntryContent,
- })
base := pluginruntime.CompiledEntry{
PluginID: util.UUIDToString(row.PluginID),
PluginKey: row.PluginKey,
@@ -720,9 +821,71 @@ func (s *PluginService) reconcileWorkspaceTx(ctx context.Context, q *db.Queries,
EntryDigest: row.EntryDigest,
RequiredDaemonFeatures: features,
Ordinal: row.Ordinal,
- SkillBundleHash: bundleManifest.Hash,
- SkillSizeBytes: bundleManifest.SizeBytes,
- SkillFileCount: bundleManifest.FileCount,
+ }
+ switch row.ContributionType {
+ case plugincontract.ContributionAgentSkillV1:
+ releaseKey := util.UUIDToString(row.ReleaseID)
+ artifactFiles, ok := releaseFiles[releaseKey]
+ if !ok {
+ artifactFiles, err = q.ListPluginArtifactFilesByRelease(ctx, row.ReleaseID)
+ if err != nil {
+ return db.PluginCapabilitySnapshot{}, fmt.Errorf("load plugin Skill artifacts: %w", err)
+ }
+ releaseFiles[releaseKey] = artifactFiles
+ }
+ pinnedFiles, bundleFiles, err := compilePluginSkillFiles(row.ReleaseID, row.ContributionKey, row.EntryPath, artifactFiles)
+ if err != nil {
+ return db.PluginCapabilitySnapshot{}, fmt.Errorf("compile plugin Skill %s: %w", row.ContributionKey, err)
+ }
+ bundleManifest := skillbundle.BuildManifest(skillbundle.Skill{
+ ID: "plugin:" + util.UUIDToString(row.ContributionID),
+ Source: skillbundle.SourcePlugin,
+ Name: row.ContributionKey,
+ Description: row.Description,
+ Content: row.EntryContent,
+ Files: bundleFiles,
+ })
+ base.SkillBundleHash = bundleManifest.Hash
+ base.SkillSizeBytes = bundleManifest.SizeBytes
+ base.SkillFileCount = bundleManifest.FileCount
+ base.SkillFiles = pinnedFiles
+ case plugincontract.ContributionRemoteMCPV1:
+ if !row.ConfigID.Valid || !row.ConfigRevision.Valid || !row.Endpoint.Valid || !row.AuthType.Valid || !row.FailurePolicy.Valid || !row.SchemaDigest.Valid {
+ return db.PluginCapabilitySnapshot{}, fmt.Errorf("remote MCP contribution %s has incomplete reviewed configuration", row.ContributionKey)
+ }
+ var tools []pluginruntime.RemoteMCPTool
+ if err := json.Unmarshal(row.ApprovedTools, &tools); err != nil || len(tools) == 0 {
+ return db.PluginCapabilitySnapshot{}, fmt.Errorf("remote MCP contribution %s has invalid approved tools", row.ContributionKey)
+ }
+ base.ConfigID = util.UUIDToString(row.ConfigID)
+ base.ConfigRevision = row.ConfigRevision.Int64
+ base.Endpoint = row.Endpoint.String
+ base.PublicConfig = append(json.RawMessage(nil), row.PublicConfig...)
+ base.SecretRef = util.UUIDToString(row.SecretRef)
+ base.AuthType = row.AuthType.String
+ base.AuthHeader = row.AuthHeader.String
+ base.ApprovedTools = tools
+ base.ToolSchemaDigest = row.SchemaDigest.String
+ base.FailurePolicy = row.FailurePolicy.String
+ var manifest plugincontract.Manifest
+ if err := json.Unmarshal([]byte(row.EntryContent), &manifest); err != nil {
+ return db.PluginCapabilitySnapshot{}, fmt.Errorf("remote MCP contribution %s has invalid manifest entry", row.ContributionKey)
+ }
+ foundDeclaration := false
+ for _, declaration := range manifest.Contributes.RemoteMCP {
+ if declaration.Key == row.ContributionKey {
+ base.Transport = declaration.Transport
+ base.ProtocolVersions = append([]string(nil), declaration.ProtocolVersions...)
+ base.EndpointAllowedHosts = append([]string(nil), declaration.EndpointPolicy.AllowedHosts...)
+ foundDeclaration = true
+ break
+ }
+ }
+ if !foundDeclaration {
+ return db.PluginCapabilitySnapshot{}, fmt.Errorf("remote MCP contribution %s is absent from its manifest entry", row.ContributionKey)
+ }
+ default:
+ return db.PluginCapabilitySnapshot{}, fmt.Errorf("unsupported plugin contribution type %q", row.ContributionType)
}
var workspaceBinding *db.ListPluginCompilationContributionsRow
diff --git a/server/internal/service/plugin_integration_test.go b/server/internal/service/plugin_integration_test.go
index ef438a4326..60bab13f49 100644
--- a/server/internal/service/plugin_integration_test.go
+++ b/server/internal/service/plugin_integration_test.go
@@ -258,6 +258,12 @@ func TestReferencePluginInstallEnablePinDisableAndRetry(t *testing.T) {
if err != nil || len(privateV1Bundles) != 1 || privateV1Manifest == nil || !strings.Contains(privateV1Bundles[0].Content, "# Incident triage") {
t.Fatalf("private v1 Skill missing from real task: bundles=%d manifest=%+v err=%v", len(privateV1Bundles), privateV1Manifest, err)
}
+ if len(privateV1Bundles[0].Files) != 1 || privateV1Bundles[0].Files[0].Path != "references/severity-guide.md" || !strings.Contains(privateV1Bundles[0].Files[0].Content, "SEV-1") {
+ t.Fatalf("private v1 Skill companion files = %#v", privateV1Bundles[0].Files)
+ }
+ if len(privateV1Manifest.OrderedContributions) != 1 || len(privateV1Manifest.OrderedContributions[0].SkillFiles) != 1 || privateV1Manifest.OrderedContributions[0].SkillFileCount != 1 {
+ t.Fatalf("private v1 execution manifest did not pin companion files: %+v", privateV1Manifest.OrderedContributions)
+ }
if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, privateV1TaskID); err != nil {
t.Fatalf("complete private v1 task: %v", err)
}
@@ -295,10 +301,28 @@ func TestReferencePluginInstallEnablePinDisableAndRetry(t *testing.T) {
if err != nil {
t.Fatalf("upgrade private Plugin: %v", err)
}
+ // Simulate an installation upgraded by an older server that retained only
+ // the release metadata and missed a newly requested capability grant. An
+ // idempotent upload must repair the missing grant and recompile the active
+ // snapshot so the contribution reaches the next task.
+ if _, err := pool.Exec(ctx, `
+ DELETE FROM plugin_grant
+ WHERE installation_id = $1 AND capability = 'agent.skill.contribute'
+ `, privateInstallation.ID); err != nil {
+ t.Fatalf("remove private Plugin grant: %v", err)
+ }
idempotentInstallation, err := pluginService.InstallPrivateArchive(ctx, workspaceUUID, actorUUID, privateArchiveV2)
if err != nil || idempotentInstallation.ID != privateInstallation.ID {
t.Fatalf("idempotent private upload: installation=%+v err=%v", idempotentInstallation, err)
}
+ var repairedGrant string
+ if err := pool.QueryRow(ctx, `
+ SELECT decision FROM plugin_grant
+ WHERE installation_id = $1 AND capability = 'agent.skill.contribute'
+ ORDER BY grant_revision DESC LIMIT 1
+ `, privateInstallation.ID).Scan(&repairedGrant); err != nil || repairedGrant != "granted" {
+ t.Fatalf("private Plugin grant was not repaired: decision=%q err=%v", repairedGrant, err)
+ }
repackedArchive := repackPluginArchive(t, privateArchiveV2)
if bytes.Equal(repackedArchive, privateArchiveV2) {
t.Fatal("repacked Private Plugin archive unexpectedly has identical bytes")
@@ -411,6 +435,9 @@ func TestReferencePluginInstallEnablePinDisableAndRetry(t *testing.T) {
if err != nil || len(historicalBundles) != 1 || historicalManifest.SnapshotDigest != privateV1Manifest.SnapshotDigest {
t.Fatalf("uninstall changed historical private task: bundles=%d manifest=%+v err=%v", len(historicalBundles), historicalManifest, err)
}
+ if len(historicalBundles[0].Files) != 1 || historicalBundles[0].Files[0].Path != "references/severity-guide.md" {
+ t.Fatalf("uninstall changed historical private Skill companion files: %#v", historicalBundles[0].Files)
+ }
afterUninstallTaskID := createTask(nil)
afterUninstallBundles, _, _, err := taskService.LoadTaskPluginSkillBundles(ctx, util.MustParseUUID(afterUninstallTaskID))
if err != nil || len(afterUninstallBundles) != 0 {
diff --git a/server/internal/service/plugin_remote_mcp.go b/server/internal/service/plugin_remote_mcp.go
new file mode 100644
index 0000000000..425871fd20
--- /dev/null
+++ b/server/internal/service/plugin_remote_mcp.go
@@ -0,0 +1,690 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "regexp"
+ "strings"
+
+ "github.com/jackc/pgx/v5"
+ "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/pluginruntime"
+ "github.com/multica-ai/multica/server/pkg/remotemcp"
+)
+
+type RemoteMCPSecretBox interface {
+ Seal([]byte) ([]byte, error)
+ Open([]byte) ([]byte, error)
+}
+
+type RemoteMCPConfigInput struct {
+ Endpoint string
+ PublicConfig json.RawMessage
+ AuthType string
+ AuthHeader string
+ Credential string
+ FailurePolicy string
+}
+
+type RemoteMCPConfigResult struct {
+ Config db.PluginInstallationConfig
+ DiscoveredTools []pluginruntime.RemoteMCPTool
+ SchemaDigest string
+}
+
+func (s *PluginService) TestRemoteMCP(ctx context.Context, workspaceID, installationID pgtype.UUID, contributionKey string) (RemoteMCPConfigResult, error) {
+ contribution, declaration, err := s.loadRemoteMCPDeclaration(ctx, s.Queries, workspaceID, installationID, contributionKey)
+ if err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ latest, err := s.Queries.GetLatestPluginInstallationConfig(ctx, db.GetLatestPluginInstallationConfigParams{
+ WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,
+ })
+ if err != nil {
+ return RemoteMCPConfigResult{}, newPluginError(PluginErrorConflict, "Remote MCP is not configured", err)
+ }
+ headers, err := s.remoteMCPHeaders(ctx, workspaceID, installationID, contribution.ID, latest.AuthType, latest.AuthHeader, "", latest.SecretRef)
+ if err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ tools, digest, err := remotemcp.Discover(ctx, latest.Endpoint, declaration.EndpointPolicy.AllowedHosts, declaration.ProtocolVersions, headers)
+ if err != nil {
+ return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "Remote MCP connection test failed", err)
+ }
+ applyDeclaredRisk(tools, declaration)
+ return RemoteMCPConfigResult{Config: latest, DiscoveredTools: tools, SchemaDigest: digest}, nil
+}
+
+var remoteMCPHeaderPattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9-]{0,127}$`)
+
+func (s *PluginService) ConfigureRemoteMCP(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, contributionKey string, input RemoteMCPConfigInput) (RemoteMCPConfigResult, error) {
+ contribution, declaration, err := s.loadRemoteMCPDeclaration(ctx, s.Queries, workspaceID, installationID, contributionKey)
+ if err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ if _, err := remotemcp.ValidatePublicHTTPSEndpoint(ctx, input.Endpoint, declaration.EndpointPolicy.AllowedHosts, nil); err != nil {
+ return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "Remote MCP endpoint is not allowed", err)
+ }
+ publicConfig, err := validateRemoteMCPPublicConfig(input.PublicConfig, declaration.ConfigurationSchema)
+ if err != nil {
+ return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "Remote MCP public configuration is invalid", err)
+ }
+ input.AuthType = strings.TrimSpace(input.AuthType)
+ input.AuthHeader = strings.TrimSpace(input.AuthHeader)
+ input.FailurePolicy = strings.TrimSpace(input.FailurePolicy)
+ if input.FailurePolicy == "" {
+ input.FailurePolicy = "required"
+ }
+ if input.FailurePolicy != "required" && input.FailurePolicy != "optional" {
+ return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "failure_policy must be required or optional", nil)
+ }
+ if input.AuthType != "none" && input.AuthType != "bearer" && input.AuthType != "header" {
+ return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "auth_type must be none, bearer, or header", nil)
+ }
+ if input.AuthType == "bearer" {
+ input.AuthHeader = "Authorization"
+ }
+ if input.AuthType == "header" && !validRemoteMCPAuthHeader(input.AuthHeader) {
+ return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "auth_header is invalid", nil)
+ }
+ if input.AuthType == "none" && input.Credential != "" {
+ return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "credential is not allowed with auth_type none", nil)
+ }
+
+ var existingSecret pgtype.UUID
+ if input.AuthType != "none" && input.Credential == "" {
+ latest, latestErr := s.Queries.GetLatestPluginInstallationConfig(ctx, db.GetLatestPluginInstallationConfigParams{
+ WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,
+ })
+ if latestErr != nil || !latest.SecretRef.Valid || latest.AuthType != input.AuthType || latest.AuthHeader != input.AuthHeader {
+ return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "credential is required", nil)
+ }
+ existingSecret = latest.SecretRef
+ }
+ headers, err := s.remoteMCPHeaders(ctx, workspaceID, installationID, contribution.ID, input.AuthType, input.AuthHeader, input.Credential, existingSecret)
+ if err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ discovered, digest, err := remotemcp.Discover(ctx, input.Endpoint, declaration.EndpointPolicy.AllowedHosts, declaration.ProtocolVersions, headers)
+ if err != nil {
+ return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "Remote MCP connection test failed", err)
+ }
+ applyDeclaredRisk(discovered, declaration)
+ discoveredJSON, _ := json.Marshal(discovered)
+
+ tx, err := s.TxStarter.Begin(ctx)
+ if err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ defer tx.Rollback(ctx) //nolint:errcheck
+ q := s.Queries.WithTx(tx)
+ secretRef := existingSecret
+ if input.AuthType != "none" && input.Credential != "" {
+ if _, lockErr := q.LockPluginRemoteMCPInstallation(ctx, db.LockPluginRemoteMCPInstallationParams{
+ WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,
+ }); lockErr != nil {
+ return RemoteMCPConfigResult{}, lockErr
+ }
+ if s.RemoteMCPSecrets == nil {
+ return RemoteMCPConfigResult{}, newPluginError(PluginErrorIncompatible, "Remote MCP credential encryption is not configured", nil)
+ }
+ sealed, sealErr := s.RemoteMCPSecrets.Seal([]byte(input.Credential))
+ if sealErr != nil {
+ return RemoteMCPConfigResult{}, fmt.Errorf("encrypt Remote MCP credential: %w", sealErr)
+ }
+ if _, revokeErr := q.RevokePluginRemoteMCPSecrets(ctx, db.RevokePluginRemoteMCPSecretsParams{
+ WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,
+ }); revokeErr != nil {
+ return RemoteMCPConfigResult{}, revokeErr
+ }
+ secret, createErr := q.CreatePluginRemoteMCPSecret(ctx, db.CreatePluginRemoteMCPSecretParams{
+ WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,
+ Ciphertext: sealed, Hint: secretHint(input.Credential), CreatedBy: actorID,
+ })
+ if createErr != nil {
+ return RemoteMCPConfigResult{}, createErr
+ }
+ secretRef = secret.ID
+ }
+ config, err := q.CreatePluginInstallationConfig(ctx, db.CreatePluginInstallationConfigParams{
+ WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,
+ Endpoint: input.Endpoint, PublicConfig: publicConfig, AuthType: input.AuthType, AuthHeader: input.AuthHeader,
+ SecretRef: secretRef, DiscoveredTools: discoveredJSON,
+ DiscoveredSchemaDigest: pgtype.Text{String: digest, Valid: true},
+ ApprovedTools: []byte(`[]`), FailurePolicy: input.FailurePolicy, CreatedBy: actorID,
+ })
+ if err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ if _, err := s.bumpPluginConfigurationGeneration(ctx, q, workspaceID, installationID, actorID); err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ return RemoteMCPConfigResult{Config: config, DiscoveredTools: discovered, SchemaDigest: digest}, nil
+}
+
+func validRemoteMCPAuthHeader(header string) bool {
+ if !remoteMCPHeaderPattern.MatchString(header) {
+ return false
+ }
+ for _, forbidden := range []string{
+ "Host", "Connection", "Content-Length", "Content-Type", "Accept",
+ "Transfer-Encoding", "Trailer", "Upgrade", "Proxy-Authorization",
+ "Mcp-Session-Id", "Mcp-Protocol-Version", "Last-Event-ID",
+ } {
+ if strings.EqualFold(header, forbidden) {
+ return false
+ }
+ }
+ return true
+}
+
+func (s *PluginService) ReviewRemoteMCPTools(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, contributionKey string, approvedNames []string) (RemoteMCPConfigResult, error) {
+ contribution, declaration, err := s.loadRemoteMCPDeclaration(ctx, s.Queries, workspaceID, installationID, contributionKey)
+ if err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ latest, err := s.Queries.GetLatestPluginInstallationConfig(ctx, db.GetLatestPluginInstallationConfigParams{
+ WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,
+ })
+ if err != nil {
+ return RemoteMCPConfigResult{}, newPluginError(PluginErrorConflict, "Remote MCP must be configured before tool review", err)
+ }
+ headers, err := s.remoteMCPHeaders(ctx, workspaceID, installationID, contribution.ID, latest.AuthType, latest.AuthHeader, "", latest.SecretRef)
+ if err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ discovered, discoveredDigest, err := remotemcp.Discover(ctx, latest.Endpoint, declaration.EndpointPolicy.AllowedHosts, declaration.ProtocolVersions, headers)
+ if err != nil {
+ return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "Remote MCP tool discovery failed", err)
+ }
+ applyDeclaredRisk(discovered, declaration)
+ approved, err := selectApprovedRemoteMCPTools(discovered, declaration, approvedNames)
+ if err != nil {
+ return RemoteMCPConfigResult{}, newPluginError(PluginErrorInvalid, "Remote MCP tool approval is invalid", err)
+ }
+ digest, err := remotemcp.ToolSetDigest(approved)
+ if err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ approvedJSON, _ := json.Marshal(approved)
+ discoveredJSON, _ := json.Marshal(discovered)
+
+ tx, err := s.TxStarter.Begin(ctx)
+ if err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ defer tx.Rollback(ctx) //nolint:errcheck
+ q := s.Queries.WithTx(tx)
+ config, err := q.CreatePluginInstallationConfig(ctx, db.CreatePluginInstallationConfigParams{
+ WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,
+ Endpoint: latest.Endpoint, PublicConfig: latest.PublicConfig, AuthType: latest.AuthType, AuthHeader: latest.AuthHeader,
+ SecretRef: latest.SecretRef, DiscoveredTools: discoveredJSON,
+ DiscoveredSchemaDigest: pgtype.Text{String: discoveredDigest, Valid: true}, ApprovedTools: approvedJSON,
+ SchemaDigest: pgtype.Text{String: digest, Valid: true}, FailurePolicy: latest.FailurePolicy,
+ ReviewedBy: actorID, CreatedBy: actorID,
+ })
+ if err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ if _, err := s.bumpPluginConfigurationGeneration(ctx, q, workspaceID, installationID, actorID); err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return RemoteMCPConfigResult{}, err
+ }
+ return RemoteMCPConfigResult{Config: config, DiscoveredTools: discovered, SchemaDigest: digest}, nil
+}
+
+func (s *PluginService) RevokeRemoteMCPCredential(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, contributionKey string) error {
+ contribution, _, err := s.loadRemoteMCPDeclaration(ctx, s.Queries, workspaceID, installationID, contributionKey)
+ if err != nil {
+ return err
+ }
+ tx, err := s.TxStarter.Begin(ctx)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback(ctx) //nolint:errcheck
+ q := s.Queries.WithTx(tx)
+ if _, err := q.LockPluginRemoteMCPInstallation(ctx, db.LockPluginRemoteMCPInstallationParams{
+ WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,
+ }); err != nil {
+ return err
+ }
+ if _, err := q.RevokePluginRemoteMCPSecrets(ctx, db.RevokePluginRemoteMCPSecretsParams{
+ WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contribution.ID,
+ }); err != nil {
+ return err
+ }
+ installation, err := q.GetPluginInstallation(ctx, installationID)
+ if err != nil {
+ return err
+ }
+ if _, err := q.SetPluginInstallationDesiredState(ctx, db.SetPluginInstallationDesiredStateParams{
+ Enabled: false, UpdatedBy: actorID, WorkspaceID: workspaceID,
+ DesiredReleaseID: installation.DesiredReleaseID, ID: installationID,
+ }); err != nil {
+ return err
+ }
+ if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {
+ return err
+ }
+ return tx.Commit(ctx)
+}
+
+// ResolveTaskRemoteMCPConnections returns only pinned connection metadata.
+// Credentials stay server-side and are resolved by the daemon broker's
+// authenticated, task-scoped endpoint immediately before an upstream call.
+func (s *PluginService) ResolveTaskRemoteMCPConnections(ctx context.Context, taskID pgtype.UUID) ([]pluginruntime.RemoteMCPConnection, []string, error) {
+ manifest, err := s.Queries.GetPluginExecutionManifestByTask(ctx, taskID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil, nil
+ }
+ if err != nil {
+ return nil, nil, err
+ }
+ entries, err := pluginruntime.ParseEntries(manifest.OrderedContributions)
+ if err != nil {
+ return nil, nil, err
+ }
+ connections := make([]pluginruntime.RemoteMCPConnection, 0)
+ diagnostics := make([]string, 0)
+ for _, entry := range entries {
+ if entry.ContributionType != plugincontract.ContributionRemoteMCPV1 {
+ continue
+ }
+ connection, _, resolveErr := s.resolveTaskRemoteMCPEntry(ctx, manifest.WorkspaceID, entry, false)
+ if resolveErr != nil {
+ if entry.FailurePolicy == "optional" {
+ diagnostics = append(diagnostics, fmt.Sprintf("optional Remote MCP %s unavailable", entry.ContributionKey))
+ continue
+ }
+ return nil, diagnostics, fmt.Errorf("required Remote MCP %s is unavailable: %w", entry.ContributionKey, resolveErr)
+ }
+ connections = append(connections, connection)
+ }
+ return connections, diagnostics, nil
+}
+
+// ResolveTaskRemoteMCPCredential re-checks the active secret row for every
+// broker call. This is the revocation boundary for already-running tasks: a
+// revoked or rotated pinned credential becomes unusable before another
+// upstream request is made.
+func (s *PluginService) ResolveTaskRemoteMCPCredential(ctx context.Context, taskID pgtype.UUID, contributionID string) (string, string, error) {
+ manifest, err := s.Queries.GetPluginExecutionManifestByTask(ctx, taskID)
+ if err != nil {
+ return "", "", newPluginError(PluginErrorNotFound, "Remote MCP task credential not found", err)
+ }
+ entries, err := pluginruntime.ParseEntries(manifest.OrderedContributions)
+ if err != nil {
+ return "", "", err
+ }
+ for _, entry := range entries {
+ if entry.ContributionType != plugincontract.ContributionRemoteMCPV1 || entry.ContributionID != contributionID {
+ continue
+ }
+ connection, credential, err := s.resolveTaskRemoteMCPEntry(ctx, manifest.WorkspaceID, entry, true)
+ if err != nil {
+ return "", "", newPluginError(PluginErrorConflict, "Remote MCP credential is revoked or unavailable", err)
+ }
+ return connection.CredentialHeader, credential, nil
+ }
+ return "", "", newPluginError(PluginErrorNotFound, "Remote MCP task contribution not found", nil)
+}
+
+func (s *PluginService) resolveTaskRemoteMCPEntry(ctx context.Context, workspaceID pgtype.UUID, entry pluginruntime.CompiledEntry, resolveCredential bool) (pluginruntime.RemoteMCPConnection, string, error) {
+ installationID, err := parsePluginRuntimeUUID(entry.InstallationID, "installation")
+ if err != nil {
+ return pluginruntime.RemoteMCPConnection{}, "", err
+ }
+ contributionID, err := parsePluginRuntimeUUID(entry.ContributionID, "contribution")
+ if err != nil {
+ return pluginruntime.RemoteMCPConnection{}, "", err
+ }
+ if entry.ConfigID == "" || entry.ConfigRevision <= 0 || entry.Endpoint == "" || entry.Transport != "streamable-http" || len(entry.ApprovedTools) == 0 {
+ return pluginruntime.RemoteMCPConnection{}, "", errors.New("pinned configuration is incomplete")
+ }
+ if _, err := remotemcp.ValidatePublicHTTPSEndpoint(ctx, entry.Endpoint, entry.EndpointAllowedHosts, nil); err != nil {
+ return pluginruntime.RemoteMCPConnection{}, "", err
+ }
+ digest, err := remotemcp.ToolSetDigest(entry.ApprovedTools)
+ if err != nil || digest != entry.ToolSchemaDigest {
+ return pluginruntime.RemoteMCPConnection{}, "", errors.New("pinned tool schema digest is invalid")
+ }
+ credentialHeader := ""
+ credential := ""
+ if entry.AuthType != "none" {
+ secretID, err := parsePluginRuntimeUUID(entry.SecretRef, "credential")
+ if err != nil || s.RemoteMCPSecrets == nil {
+ return pluginruntime.RemoteMCPConnection{}, "", errors.New("credential is unavailable")
+ }
+ credentialHeader = entry.AuthHeader
+ if entry.AuthType == "oauth" {
+ credentialHeader = "Authorization"
+ if resolveCredential {
+ accessToken, err := s.remoteMCPOAuthAccessToken(ctx, workspaceID, installationID, contributionID, secretID)
+ if err != nil {
+ return pluginruntime.RemoteMCPConnection{}, "", errors.New("OAuth connection is expired or unavailable")
+ }
+ credential = "Bearer " + accessToken
+ } else if _, err := s.Queries.GetActivePluginRemoteMCPSecret(ctx, db.GetActivePluginRemoteMCPSecretParams{
+ ID: secretID, WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contributionID,
+ }); err != nil {
+ return pluginruntime.RemoteMCPConnection{}, "", errors.New("credential is revoked or outside task scope")
+ }
+ } else {
+ secret, err := s.Queries.GetActivePluginRemoteMCPSecret(ctx, db.GetActivePluginRemoteMCPSecretParams{
+ ID: secretID, WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contributionID,
+ })
+ if err != nil {
+ return pluginruntime.RemoteMCPConnection{}, "", errors.New("credential is revoked or outside task scope")
+ }
+ if resolveCredential {
+ opened, err := s.RemoteMCPSecrets.Open(secret.Ciphertext)
+ if err != nil {
+ return pluginruntime.RemoteMCPConnection{}, "", errors.New("credential cannot be decrypted")
+ }
+ credential = string(opened)
+ }
+ }
+ if resolveCredential && entry.AuthType == "bearer" {
+ credentialHeader = "Authorization"
+ credential = "Bearer " + credential
+ }
+ }
+ return pluginruntime.RemoteMCPConnection{
+ InstallationID: entry.InstallationID, ContributionID: entry.ContributionID,
+ ContributionKey: entry.ContributionKey, ConfigID: entry.ConfigID, ConfigRevision: entry.ConfigRevision,
+ Endpoint: entry.Endpoint, PublicConfig: append(json.RawMessage(nil), entry.PublicConfig...),
+ Transport: entry.Transport, ProtocolVersions: append([]string(nil), entry.ProtocolVersions...),
+ EndpointAllowedHosts: append([]string(nil), entry.EndpointAllowedHosts...),
+ CredentialHeader: credentialHeader,
+ ApprovedTools: append([]pluginruntime.RemoteMCPTool(nil), entry.ApprovedTools...),
+ ToolSchemaDigest: entry.ToolSchemaDigest, FailurePolicy: entry.FailurePolicy,
+ }, credential, nil
+}
+
+func parsePluginRuntimeUUID(value, field string) (pgtype.UUID, error) {
+ var id pgtype.UUID
+ if err := id.Scan(value); err != nil || !id.Valid {
+ return pgtype.UUID{}, fmt.Errorf("invalid %s id", field)
+ }
+ return id, nil
+}
+
+func (s *PluginService) loadRemoteMCPDeclaration(ctx context.Context, q *db.Queries, workspaceID, installationID pgtype.UUID, contributionKey string) (db.GetInstallationRemoteMCPContributionRow, plugincontract.RemoteMCPContribution, error) {
+ row, err := q.GetInstallationRemoteMCPContribution(ctx, db.GetInstallationRemoteMCPContributionParams{
+ WorkspaceID: workspaceID, InstallationID: installationID, ContributionKey: contributionKey,
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ return row, plugincontract.RemoteMCPContribution{}, newPluginError(PluginErrorNotFound, "Remote MCP contribution not found", nil)
+ }
+ if err != nil {
+ return row, plugincontract.RemoteMCPContribution{}, err
+ }
+ var manifest plugincontract.Manifest
+ if err := json.Unmarshal(row.Manifest, &manifest); err != nil {
+ return row, plugincontract.RemoteMCPContribution{}, err
+ }
+ for _, declaration := range manifest.Contributes.RemoteMCP {
+ if declaration.Key == contributionKey {
+ return row, declaration, nil
+ }
+ }
+ return row, plugincontract.RemoteMCPContribution{}, newPluginError(PluginErrorNotFound, "Remote MCP contribution not found", nil)
+}
+
+func (s *PluginService) remoteMCPHeaders(ctx context.Context, workspaceID, installationID, contributionID pgtype.UUID, authType, authHeader, plaintext string, secretRef pgtype.UUID) (http.Header, error) {
+ headers := make(http.Header)
+ if authType == "none" {
+ return headers, nil
+ }
+ if authType == "oauth" {
+ if !secretRef.Valid {
+ return nil, newPluginError(PluginErrorConflict, "Remote MCP OAuth connection is unavailable", nil)
+ }
+ accessToken, err := s.remoteMCPOAuthAccessToken(ctx, workspaceID, installationID, contributionID, secretRef)
+ if err != nil {
+ return nil, newPluginError(PluginErrorConflict, "Remote MCP OAuth connection is unavailable", err)
+ }
+ headers.Set("Authorization", "Bearer "+accessToken)
+ return headers, nil
+ }
+ if plaintext == "" {
+ if s.RemoteMCPSecrets == nil || !secretRef.Valid {
+ return nil, newPluginError(PluginErrorConflict, "Remote MCP credential is unavailable", nil)
+ }
+ secret, err := s.Queries.GetActivePluginRemoteMCPSecret(ctx, db.GetActivePluginRemoteMCPSecretParams{
+ ID: secretRef, WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contributionID,
+ })
+ if err != nil {
+ return nil, newPluginError(PluginErrorConflict, "Remote MCP credential is unavailable", err)
+ }
+ opened, err := s.RemoteMCPSecrets.Open(secret.Ciphertext)
+ if err != nil {
+ return nil, newPluginError(PluginErrorConflict, "Remote MCP credential is unavailable", err)
+ }
+ plaintext = string(opened)
+ }
+ if authType == "bearer" {
+ headers.Set("Authorization", "Bearer "+plaintext)
+ } else {
+ headers.Set(authHeader, plaintext)
+ }
+ return headers, nil
+}
+
+func (s *PluginService) bumpPluginConfigurationGeneration(ctx context.Context, q *db.Queries, workspaceID, installationID, actorID pgtype.UUID) (db.PluginInstallation, error) {
+ installation, err := q.GetPluginInstallation(ctx, installationID)
+ if err != nil || installation.WorkspaceID != workspaceID {
+ return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin installation not found", nil)
+ }
+ return q.SetPluginInstallationDesiredState(ctx, db.SetPluginInstallationDesiredStateParams{
+ Enabled: installation.Enabled, UpdatedBy: actorID, WorkspaceID: workspaceID,
+ DesiredReleaseID: installation.DesiredReleaseID, ID: installationID,
+ })
+}
+
+func validateRemoteMCPPublicConfig(raw, rawSchema json.RawMessage) ([]byte, error) {
+ if len(raw) == 0 {
+ raw = json.RawMessage(`{}`)
+ }
+ var config map[string]any
+ if err := json.Unmarshal(raw, &config); err != nil {
+ return nil, err
+ }
+ if err := rejectRemoteMCPSecretKeys(config, ""); err != nil {
+ return nil, err
+ }
+ if len(rawSchema) > 0 {
+ var schema map[string]any
+ if err := json.Unmarshal(rawSchema, &schema); err != nil {
+ return nil, err
+ }
+ if err := validateRemoteMCPConfigValue(config, schema, "configuration"); err != nil {
+ return nil, err
+ }
+ }
+ return json.Marshal(config)
+}
+
+func rejectRemoteMCPSecretKeys(value any, path string) error {
+ switch typed := value.(type) {
+ case map[string]any:
+ for key, child := range typed {
+ childPath := key
+ if path != "" {
+ childPath = path + "." + key
+ }
+ normalized := strings.ToLower(strings.ReplaceAll(key, "-", "_"))
+ if strings.Contains(normalized, "secret") || strings.Contains(normalized, "token") || strings.Contains(normalized, "password") || strings.Contains(normalized, "authorization") || strings.Contains(normalized, "api_key") {
+ return fmt.Errorf("public configuration key %q may contain a secret", childPath)
+ }
+ if err := rejectRemoteMCPSecretKeys(child, childPath); err != nil {
+ return err
+ }
+ }
+ case []any:
+ for index, child := range typed {
+ if err := rejectRemoteMCPSecretKeys(child, fmt.Sprintf("%s[%d]", path, index)); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// validateRemoteMCPConfigValue intentionally implements the safe structural
+// subset accepted by the V1 manifest contract. Publishers can constrain object
+// properties, required fields, arrays, primitive types, and enums; unsupported
+// JSON Schema keywords remain annotations and never broaden this validation.
+func validateRemoteMCPConfigValue(value any, schema map[string]any, path string) error {
+ if choices, ok := schema["enum"].([]any); ok {
+ matched := false
+ for _, choice := range choices {
+ left, _ := json.Marshal(value)
+ right, _ := json.Marshal(choice)
+ if string(left) == string(right) {
+ matched = true
+ break
+ }
+ }
+ if !matched {
+ return fmt.Errorf("%s is outside the configured enum", path)
+ }
+ }
+ typeName, _ := schema["type"].(string)
+ switch typeName {
+ case "", "object":
+ object, ok := value.(map[string]any)
+ if !ok {
+ return fmt.Errorf("%s must be an object", path)
+ }
+ properties, _ := schema["properties"].(map[string]any)
+ required, _ := schema["required"].([]any)
+ for _, rawName := range required {
+ name, _ := rawName.(string)
+ if _, exists := object[name]; name != "" && !exists {
+ return fmt.Errorf("%s.%s is required", path, name)
+ }
+ }
+ additional, hasAdditional := schema["additionalProperties"].(bool)
+ for name, child := range object {
+ rawChildSchema, exists := properties[name]
+ if !exists {
+ if hasAdditional && !additional {
+ return fmt.Errorf("%s.%s is not allowed", path, name)
+ }
+ continue
+ }
+ childSchema, ok := rawChildSchema.(map[string]any)
+ if !ok {
+ return fmt.Errorf("%s.%s has an invalid schema", path, name)
+ }
+ if err := validateRemoteMCPConfigValue(child, childSchema, path+"."+name); err != nil {
+ return err
+ }
+ }
+ case "array":
+ items, ok := value.([]any)
+ if !ok {
+ return fmt.Errorf("%s must be an array", path)
+ }
+ itemSchema, _ := schema["items"].(map[string]any)
+ for index, item := range items {
+ if itemSchema != nil {
+ if err := validateRemoteMCPConfigValue(item, itemSchema, fmt.Sprintf("%s[%d]", path, index)); err != nil {
+ return err
+ }
+ }
+ }
+ case "string":
+ if _, ok := value.(string); !ok {
+ return fmt.Errorf("%s must be a string", path)
+ }
+ case "boolean":
+ if _, ok := value.(bool); !ok {
+ return fmt.Errorf("%s must be a boolean", path)
+ }
+ case "number":
+ if _, ok := value.(float64); !ok {
+ return fmt.Errorf("%s must be a number", path)
+ }
+ case "integer":
+ number, ok := value.(float64)
+ if !ok || number != float64(int64(number)) {
+ return fmt.Errorf("%s must be an integer", path)
+ }
+ case "null":
+ if value != nil {
+ return fmt.Errorf("%s must be null", path)
+ }
+ default:
+ return fmt.Errorf("%s uses unsupported schema type %q", path, typeName)
+ }
+ return nil
+}
+
+func applyDeclaredRisk(tools []pluginruntime.RemoteMCPTool, declaration plugincontract.RemoteMCPContribution) {
+ risks := make(map[string]string, len(declaration.ToolIntent))
+ for _, intent := range declaration.ToolIntent {
+ risks[intent.Name] = intent.Risk
+ }
+ for index := range tools {
+ risk := risks[tools[index].Name]
+ if risk == "" {
+ risk = risks[plugincontract.RemoteMCPAnyToolIntent]
+ }
+ tools[index].Risk = risk
+ }
+}
+
+func selectApprovedRemoteMCPTools(discovered []pluginruntime.RemoteMCPTool, declaration plugincontract.RemoteMCPContribution, names []string) ([]pluginruntime.RemoteMCPTool, error) {
+ if len(names) == 0 {
+ return nil, errors.New("at least one tool must be approved")
+ }
+ intended := make(map[string]bool, len(declaration.ToolIntent))
+ for _, tool := range declaration.ToolIntent {
+ intended[tool.Name] = true
+ }
+ allowDiscovered := intended[plugincontract.RemoteMCPAnyToolIntent]
+ available := make(map[string]pluginruntime.RemoteMCPTool, len(discovered))
+ for _, tool := range discovered {
+ available[tool.Name] = tool
+ }
+ approved := make([]pluginruntime.RemoteMCPTool, 0, len(names))
+ seen := map[string]bool{}
+ for _, name := range names {
+ if seen[name] || (!allowDiscovered && !intended[name]) {
+ return nil, fmt.Errorf("tool %q is duplicate or outside declared intent", name)
+ }
+ tool, ok := available[name]
+ if !ok {
+ return nil, fmt.Errorf("tool %q was not discovered", name)
+ }
+ seen[name] = true
+ approved = append(approved, tool)
+ }
+ return approved, nil
+}
+
+func secretHint(secret string) string {
+ if len(secret) <= 4 {
+ return "••••"
+ }
+ return "••••" + secret[len(secret)-4:]
+}
diff --git a/server/internal/service/plugin_remote_mcp_oauth.go b/server/internal/service/plugin_remote_mcp_oauth.go
new file mode 100644
index 0000000000..49739f44ef
--- /dev/null
+++ b/server/internal/service/plugin_remote_mcp_oauth.go
@@ -0,0 +1,447 @@
+package service
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "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"
+)
+
+const remoteMCPOAuthStateTTL = 10 * time.Minute
+const remoteMCPOAuthRefreshTimeout = 10 * time.Second
+
+type RemoteMCPOAuthStartInput struct {
+ Endpoint string
+ PublicConfig json.RawMessage
+ FailurePolicy string
+ Scope string
+ ClientID string
+ ClientSecret string
+ TokenEndpointAuthMethod string
+ AuthorizationEndpoint string
+ TokenEndpoint string
+ RedirectURI string
+ ReturnTo string
+}
+
+type RemoteMCPOAuthStartResult struct {
+ AuthorizationURL string
+}
+
+type RemoteMCPOAuthCallbackResult struct {
+ ReturnTo string
+}
+
+type remoteMCPOAuthStateSecret struct {
+ Verifier string `json:"verifier"`
+ ClientSecret string `json:"client_secret,omitempty"`
+ TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
+}
+
+// remoteMCPOAuthTokenSecret is the encrypted connection record. Keeping the
+// refresh metadata beside the token means neither the Plugin artifact nor the
+// execution manifest ever receives reusable OAuth material.
+type remoteMCPOAuthTokenSecret struct {
+ AccessToken string `json:"access_token"`
+ RefreshToken string `json:"refresh_token,omitempty"`
+ ExpiresAt time.Time `json:"expires_at,omitempty"`
+ Scope string `json:"scope,omitempty"`
+ Resource string `json:"resource"`
+ TokenEndpoint string `json:"token_endpoint"`
+ ClientID string `json:"client_id"`
+ ClientSecret string `json:"client_secret,omitempty"`
+ TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
+}
+
+func (s *PluginService) BeginRemoteMCPOAuth(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, contributionKey string, input RemoteMCPOAuthStartInput) (RemoteMCPOAuthStartResult, error) {
+ if s.RemoteMCPSecrets == nil {
+ return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorIncompatible, "Remote MCP credential encryption is not configured", nil)
+ }
+ if strings.TrimSpace(input.RedirectURI) == "" {
+ return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorIncompatible, "Remote MCP OAuth callback URL is not configured", nil)
+ }
+ contribution, declaration, err := s.loadRemoteMCPDeclaration(ctx, s.Queries, workspaceID, installationID, contributionKey)
+ if err != nil {
+ return RemoteMCPOAuthStartResult{}, err
+ }
+ input.Endpoint = strings.TrimSpace(input.Endpoint)
+ if input.Endpoint == "" {
+ input.Endpoint = declaration.EndpointPolicy.DefaultEndpoint
+ }
+ if _, err := remotemcp.ValidatePublicHTTPSEndpoint(ctx, input.Endpoint, declaration.EndpointPolicy.AllowedHosts, nil); err != nil {
+ return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "Remote MCP endpoint is not allowed", err)
+ }
+ publicConfig, err := validateRemoteMCPPublicConfig(input.PublicConfig, declaration.ConfigurationSchema)
+ if err != nil {
+ return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "Remote MCP public configuration is invalid", err)
+ }
+ input.FailurePolicy = strings.TrimSpace(input.FailurePolicy)
+ if input.FailurePolicy == "" {
+ input.FailurePolicy = "required"
+ }
+ if input.FailurePolicy != "required" && input.FailurePolicy != "optional" {
+ return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "failure_policy must be required or optional", nil)
+ }
+
+ metadata, err := remotemcp.DiscoverOAuth(ctx, input.Endpoint, declaration.EndpointPolicy.AllowedHosts)
+ if err != nil {
+ return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "Remote MCP OAuth discovery failed", err)
+ }
+ if strings.TrimSpace(input.AuthorizationEndpoint) != "" || strings.TrimSpace(input.TokenEndpoint) != "" {
+ if input.AuthorizationEndpoint == "" || input.TokenEndpoint == "" {
+ return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "both OAuth endpoints are required", nil)
+ }
+ // Advanced overrides still pass through the remotemcp package's public
+ // HTTPS checks when the authorization URL is built and the token is
+ // exchanged. Discovery remains mandatory so a random MCP endpoint cannot
+ // turn Multica into an arbitrary OAuth client.
+ metadata.AuthorizationEndpoint = strings.TrimSpace(input.AuthorizationEndpoint)
+ metadata.TokenEndpoint = strings.TrimSpace(input.TokenEndpoint)
+ }
+ if err := remotemcp.ValidateOAuthMetadata(ctx, metadata); err != nil {
+ return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "Remote MCP OAuth endpoints are invalid", err)
+ }
+
+ registration := remotemcp.OAuthClientRegistration{
+ ClientID: strings.TrimSpace(input.ClientID), ClientSecret: input.ClientSecret,
+ TokenEndpointAuthMethod: strings.TrimSpace(input.TokenEndpointAuthMethod),
+ }
+ if registration.ClientID == "" {
+ registration, err = remotemcp.RegisterOAuthClient(ctx, metadata, input.RedirectURI)
+ if err != nil {
+ return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "Remote MCP OAuth client registration failed", err)
+ }
+ }
+ if registration.TokenEndpointAuthMethod == "" {
+ if registration.ClientSecret == "" {
+ registration.TokenEndpointAuthMethod = "none"
+ } else {
+ registration.TokenEndpointAuthMethod = "client_secret_basic"
+ }
+ }
+ if registration.TokenEndpointAuthMethod != "none" && registration.TokenEndpointAuthMethod != "client_secret_basic" && registration.TokenEndpointAuthMethod != "client_secret_post" {
+ return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "unsupported OAuth token endpoint authentication method", nil)
+ }
+
+ state, err := secureRemoteMCPRandom()
+ if err != nil {
+ return RemoteMCPOAuthStartResult{}, err
+ }
+ verifier, err := secureRemoteMCPRandom()
+ if err != nil {
+ return RemoteMCPOAuthStartResult{}, err
+ }
+ scope := strings.TrimSpace(input.Scope)
+ if scope == "" {
+ scope = strings.Join(metadata.Scopes, " ")
+ }
+ stateSecret, _ := json.Marshal(remoteMCPOAuthStateSecret{
+ Verifier: verifier, ClientSecret: registration.ClientSecret,
+ TokenEndpointAuthMethod: registration.TokenEndpointAuthMethod,
+ })
+ sealed, err := s.RemoteMCPSecrets.Seal(stateSecret)
+ if err != nil {
+ return RemoteMCPOAuthStartResult{}, fmt.Errorf("encrypt Remote MCP OAuth state: %w", err)
+ }
+ stateHash := sha256.Sum256([]byte(state))
+ returnTo := sanitizeRemoteMCPReturnTo(input.ReturnTo)
+ _, _ = s.Queries.DeleteExpiredPluginRemoteMCPOAuthStates(ctx)
+ if _, err := s.Queries.CreatePluginRemoteMCPOAuthState(ctx, db.CreatePluginRemoteMCPOAuthStateParams{
+ StateHash: stateHash[:], WorkspaceID: workspaceID, InstallationID: installationID,
+ ContributionID: contribution.ID, ActorID: actorID, Endpoint: metadata.ResourceEndpoint,
+ PublicConfig: publicConfig, FailurePolicy: input.FailurePolicy,
+ AuthorizationEndpoint: metadata.AuthorizationEndpoint, TokenEndpoint: metadata.TokenEndpoint,
+ ClientID: registration.ClientID, Scope: scope, RedirectUri: input.RedirectURI,
+ ReturnTo: returnTo, SecretCiphertext: sealed,
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(remoteMCPOAuthStateTTL), Valid: true},
+ }); err != nil {
+ return RemoteMCPOAuthStartResult{}, err
+ }
+ authorizationURL, err := remotemcp.BuildAuthorizationURL(metadata, registration, input.RedirectURI, state, verifier, scope)
+ if err != nil {
+ return RemoteMCPOAuthStartResult{}, newPluginError(PluginErrorInvalid, "build Remote MCP authorization URL", err)
+ }
+ return RemoteMCPOAuthStartResult{AuthorizationURL: authorizationURL}, nil
+}
+
+func (s *PluginService) CompleteRemoteMCPOAuth(ctx context.Context, state, code string) (RemoteMCPOAuthCallbackResult, error) {
+ if s.RemoteMCPSecrets == nil {
+ return RemoteMCPOAuthCallbackResult{}, newPluginError(PluginErrorIncompatible, "Remote MCP credential encryption is not configured", nil)
+ }
+ if state == "" {
+ return RemoteMCPOAuthCallbackResult{}, newPluginError(PluginErrorInvalid, "OAuth callback is missing state", nil)
+ }
+ stateHash := sha256.Sum256([]byte(state))
+ claimed, err := s.Queries.ClaimPluginRemoteMCPOAuthState(ctx, stateHash[:])
+ if errors.Is(err, pgx.ErrNoRows) {
+ return RemoteMCPOAuthCallbackResult{}, newPluginError(PluginErrorInvalid, "OAuth state is invalid, expired, or already used", nil)
+ }
+ if err != nil {
+ return RemoteMCPOAuthCallbackResult{}, err
+ }
+ if code == "" {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, newPluginError(PluginErrorInvalid, "OAuth callback did not include an authorization code", nil)
+ }
+ opened, err := s.RemoteMCPSecrets.Open(claimed.SecretCiphertext)
+ if err != nil {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, newPluginError(PluginErrorInvalid, "OAuth state cannot be decrypted", err)
+ }
+ var stateSecret remoteMCPOAuthStateSecret
+ if err := json.Unmarshal(opened, &stateSecret); err != nil || stateSecret.Verifier == "" {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, newPluginError(PluginErrorInvalid, "OAuth state is invalid", err)
+ }
+ registration := remotemcp.OAuthClientRegistration{
+ ClientID: claimed.ClientID, ClientSecret: stateSecret.ClientSecret,
+ TokenEndpointAuthMethod: stateSecret.TokenEndpointAuthMethod,
+ }
+ token, err := remotemcp.ExchangeOAuthCode(ctx, claimed.TokenEndpoint, claimed.Endpoint, code, claimed.RedirectUri, stateSecret.Verifier, registration)
+ if err != nil {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, newPluginError(PluginErrorInvalid, "Remote MCP OAuth token exchange failed", err)
+ }
+ if token.RefreshToken == "" {
+ // A non-expiring access token is usable without a refresh token. A
+ // short-lived token without one would leave a connection that appears
+ // healthy but predictably dies, so fail it at connect time.
+ if token.ExpiresIn > 0 {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, newPluginError(PluginErrorInvalid, "OAuth server returned an expiring token without refresh capability", nil)
+ }
+ }
+ headers := make(map[string][]string)
+ headers["Authorization"] = []string{"Bearer " + token.AccessToken}
+ contribution, declaration, err := s.loadRemoteMCPDeclarationByID(ctx, claimed.WorkspaceID, claimed.InstallationID, claimed.ContributionID)
+ if err != nil {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err
+ }
+ discovered, discoveredDigest, err := remotemcp.Discover(ctx, claimed.Endpoint, declaration.EndpointPolicy.AllowedHosts, declaration.ProtocolVersions, headers)
+ if err != nil {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, newPluginError(PluginErrorInvalid, "Remote MCP connection test failed after OAuth", err)
+ }
+ applyDeclaredRisk(discovered, declaration)
+ discoveredJSON, _ := json.Marshal(discovered)
+
+ tokenSecret := remoteMCPOAuthTokenSecret{
+ AccessToken: token.AccessToken, RefreshToken: token.RefreshToken,
+ ExpiresAt: remotemcp.OAuthExpiry(time.Now(), token.ExpiresIn), Scope: token.Scope,
+ Resource: claimed.Endpoint, TokenEndpoint: claimed.TokenEndpoint,
+ ClientID: claimed.ClientID, ClientSecret: stateSecret.ClientSecret,
+ TokenEndpointAuthMethod: stateSecret.TokenEndpointAuthMethod,
+ }
+ tokenJSON, _ := json.Marshal(tokenSecret)
+ sealed, err := s.RemoteMCPSecrets.Seal(tokenJSON)
+ if err != nil {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, fmt.Errorf("encrypt Remote MCP OAuth token: %w", err)
+ }
+
+ tx, err := s.TxStarter.Begin(ctx)
+ if err != nil {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err
+ }
+ defer tx.Rollback(ctx) //nolint:errcheck
+ q := s.Queries.WithTx(tx)
+ if _, err := q.LockPluginRemoteMCPInstallation(ctx, db.LockPluginRemoteMCPInstallationParams{
+ WorkspaceID: claimed.WorkspaceID, InstallationID: claimed.InstallationID, ContributionID: contribution.ID,
+ }); err != nil {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err
+ }
+ if _, err := q.RevokePluginRemoteMCPSecrets(ctx, db.RevokePluginRemoteMCPSecretsParams{
+ WorkspaceID: claimed.WorkspaceID, InstallationID: claimed.InstallationID, ContributionID: contribution.ID,
+ }); err != nil {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err
+ }
+ secret, err := q.CreatePluginRemoteMCPSecret(ctx, db.CreatePluginRemoteMCPSecretParams{
+ WorkspaceID: claimed.WorkspaceID, InstallationID: claimed.InstallationID, ContributionID: contribution.ID,
+ Ciphertext: sealed, Hint: "OAuth", CreatedBy: claimed.ActorID,
+ })
+ if err != nil {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err
+ }
+ if _, err := q.CreatePluginInstallationConfig(ctx, db.CreatePluginInstallationConfigParams{
+ WorkspaceID: claimed.WorkspaceID, InstallationID: claimed.InstallationID, ContributionID: contribution.ID,
+ Endpoint: claimed.Endpoint, PublicConfig: claimed.PublicConfig, AuthType: "oauth", AuthHeader: "Authorization",
+ SecretRef: secret.ID, DiscoveredTools: discoveredJSON,
+ DiscoveredSchemaDigest: pgtype.Text{String: discoveredDigest, Valid: true},
+ ApprovedTools: []byte(`[]`), FailurePolicy: claimed.FailurePolicy, CreatedBy: claimed.ActorID,
+ }); err != nil {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err
+ }
+ if _, err := s.bumpPluginConfigurationGeneration(ctx, q, claimed.WorkspaceID, claimed.InstallationID, claimed.ActorID); err != nil {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err
+ }
+ if _, err := s.reconcileWorkspaceTx(ctx, q, claimed.WorkspaceID); err != nil {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, err
+ }
+ return RemoteMCPOAuthCallbackResult{ReturnTo: claimed.ReturnTo}, nil
+}
+
+func (s *PluginService) loadRemoteMCPDeclarationByID(ctx context.Context, workspaceID, installationID, contributionID pgtype.UUID) (db.GetInstallationRemoteMCPContributionRow, plugincontract.RemoteMCPContribution, error) {
+ row, err := s.Queries.GetInstallationRemoteMCPContributionByID(ctx, db.GetInstallationRemoteMCPContributionByIDParams{
+ WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contributionID,
+ })
+ if err != nil {
+ return db.GetInstallationRemoteMCPContributionRow{}, plugincontract.RemoteMCPContribution{}, err
+ }
+ var manifest plugincontract.Manifest
+ if err := json.Unmarshal(row.Manifest, &manifest); err != nil {
+ return db.GetInstallationRemoteMCPContributionRow{}, plugincontract.RemoteMCPContribution{}, err
+ }
+ for _, declaration := range manifest.Contributes.RemoteMCP {
+ if declaration.Key == row.ContributionKey {
+ // sqlc generates structurally identical row types for the key and id
+ // queries, but Go treats them as distinct. Resolve once by key to keep
+ // callers on the established service type.
+ return s.loadRemoteMCPDeclaration(ctx, s.Queries, workspaceID, installationID, row.ContributionKey)
+ }
+ }
+ return db.GetInstallationRemoteMCPContributionRow{}, plugincontract.RemoteMCPContribution{}, newPluginError(PluginErrorNotFound, "Remote MCP contribution not found", nil)
+}
+
+func secureRemoteMCPRandom() (string, error) {
+ value := make([]byte, 32)
+ if _, err := rand.Read(value); err != nil {
+ return "", err
+ }
+ return base64.RawURLEncoding.EncodeToString(value), nil
+}
+
+func sanitizeRemoteMCPReturnTo(value string) string {
+ value = strings.TrimSpace(value)
+ if !strings.HasPrefix(value, "/") || strings.HasPrefix(value, "//") || strings.ContainsAny(value, "\r\n") {
+ return "/"
+ }
+ return value
+}
+
+func (s *PluginService) remoteMCPOAuthAccessToken(ctx context.Context, workspaceID, installationID, contributionID, secretID pgtype.UUID) (string, error) {
+ if s.RemoteMCPSecrets == nil {
+ return "", errors.New("credential encryption is not configured")
+ }
+ _, token, err := s.loadRemoteMCPOAuthToken(ctx, s.Queries, workspaceID, installationID, contributionID, secretID)
+ if err != nil {
+ return "", err
+ }
+ if token.ExpiresAt.IsZero() || token.ExpiresAt.After(time.Now().Add(time.Minute)) {
+ return token.AccessToken, nil
+ }
+
+ key := base64.RawURLEncoding.EncodeToString(secretID.Bytes[:])
+ value, err, _ := s.remoteMCPOAuthRefresh.Do(key, func() (any, error) {
+ secret, current, err := s.loadRemoteMCPOAuthToken(ctx, s.Queries, workspaceID, installationID, contributionID, secretID)
+ if err != nil {
+ return "", err
+ }
+ if current.ExpiresAt.IsZero() || current.ExpiresAt.After(time.Now().Add(time.Minute)) {
+ return current.AccessToken, nil
+ }
+ if current.RefreshToken == "" {
+ return "", errors.New("OAuth access token expired without a refresh token")
+ }
+
+ refreshCtx, cancel := context.WithTimeout(ctx, remoteMCPOAuthRefreshTimeout)
+ defer cancel()
+ refreshed, err := remotemcp.RefreshOAuthToken(refreshCtx, current.TokenEndpoint, current.Resource, current.RefreshToken, remotemcp.OAuthClientRegistration{
+ ClientID: current.ClientID, ClientSecret: current.ClientSecret, TokenEndpointAuthMethod: current.TokenEndpointAuthMethod,
+ })
+ if err != nil {
+ return "", err
+ }
+ current.AccessToken = refreshed.AccessToken
+ if refreshed.RefreshToken != "" {
+ current.RefreshToken = refreshed.RefreshToken
+ }
+ if refreshed.Scope != "" {
+ current.Scope = refreshed.Scope
+ }
+ current.ExpiresAt = remotemcp.OAuthExpiry(time.Now(), refreshed.ExpiresIn)
+
+ // The network call intentionally happens before the write lock. Once the
+ // provider responds, lock briefly to re-check revocation/rotation and
+ // publish the refreshed token atomically.
+ tx, err := s.TxStarter.Begin(ctx)
+ if err != nil {
+ return "", err
+ }
+ defer tx.Rollback(ctx) //nolint:errcheck
+ q := s.Queries.WithTx(tx)
+ locked, err := q.GetActivePluginRemoteMCPSecretForUpdate(ctx, db.GetActivePluginRemoteMCPSecretForUpdateParams{
+ ID: secretID, WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contributionID,
+ })
+ if err != nil {
+ return "", err
+ }
+ lockedToken, err := s.decodeRemoteMCPOAuthToken(locked.Ciphertext)
+ if err != nil {
+ return "", err
+ }
+ if lockedToken.ExpiresAt.IsZero() || lockedToken.ExpiresAt.After(time.Now().Add(time.Minute)) {
+ if err := tx.Commit(ctx); err != nil {
+ return "", err
+ }
+ return lockedToken.AccessToken, nil
+ }
+ if !bytes.Equal(locked.Ciphertext, secret.Ciphertext) {
+ return "", errors.New("OAuth token changed while it was being refreshed")
+ }
+
+ encoded, _ := json.Marshal(current)
+ sealed, err := s.RemoteMCPSecrets.Seal(encoded)
+ if err != nil {
+ return "", err
+ }
+ if _, err := q.UpdateActivePluginRemoteMCPSecret(ctx, db.UpdateActivePluginRemoteMCPSecretParams{
+ Ciphertext: sealed, Hint: "OAuth", ID: secretID, WorkspaceID: workspaceID,
+ InstallationID: installationID, ContributionID: contributionID,
+ }); err != nil {
+ return "", err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return "", err
+ }
+ return current.AccessToken, nil
+ })
+ if err != nil {
+ return "", err
+ }
+ accessToken, ok := value.(string)
+ if !ok || accessToken == "" {
+ return "", errors.New("OAuth token refresh returned no access token")
+ }
+ return accessToken, nil
+}
+
+func (s *PluginService) loadRemoteMCPOAuthToken(ctx context.Context, q *db.Queries, workspaceID, installationID, contributionID, secretID pgtype.UUID) (db.PluginRemoteMcpSecret, remoteMCPOAuthTokenSecret, error) {
+ secret, err := q.GetActivePluginRemoteMCPSecret(ctx, db.GetActivePluginRemoteMCPSecretParams{
+ ID: secretID, WorkspaceID: workspaceID, InstallationID: installationID, ContributionID: contributionID,
+ })
+ if err != nil {
+ return db.PluginRemoteMcpSecret{}, remoteMCPOAuthTokenSecret{}, err
+ }
+ token, err := s.decodeRemoteMCPOAuthToken(secret.Ciphertext)
+ return secret, token, err
+}
+
+func (s *PluginService) decodeRemoteMCPOAuthToken(ciphertext []byte) (remoteMCPOAuthTokenSecret, error) {
+ opened, err := s.RemoteMCPSecrets.Open(ciphertext)
+ if err != nil {
+ return remoteMCPOAuthTokenSecret{}, err
+ }
+ var token remoteMCPOAuthTokenSecret
+ if err := json.Unmarshal(opened, &token); err != nil || token.AccessToken == "" {
+ return remoteMCPOAuthTokenSecret{}, errors.New("OAuth token is invalid")
+ }
+ return token, nil
+}
diff --git a/server/internal/service/plugin_remote_mcp_test.go b/server/internal/service/plugin_remote_mcp_test.go
new file mode 100644
index 0000000000..ba341b2a2e
--- /dev/null
+++ b/server/internal/service/plugin_remote_mcp_test.go
@@ -0,0 +1,95 @@
+package service
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+ "github.com/multica-ai/multica/server/pkg/pluginruntime"
+)
+
+func TestValidateRemoteMCPPublicConfigRejectsNestedSecretsAndSchemaViolations(t *testing.T) {
+ schema := json.RawMessage(`{
+ "type":"object",
+ "required":["region"],
+ "properties":{"region":{"type":"string","enum":["us","eu"]}},
+ "additionalProperties":false
+ }`)
+ canonical, err := validateRemoteMCPPublicConfig(json.RawMessage(`{"region":"eu"}`), schema)
+ if err != nil || string(canonical) != `{"region":"eu"}` {
+ t.Fatalf("valid config = %s, %v", canonical, err)
+ }
+ for _, raw := range []string{
+ `{"region":"ap"}`,
+ `{"region":"eu","extra":true}`,
+ `{"region":"eu","nested":{"access_token":"secret"}}`,
+ `{"region":"eu","items":[{"password":"secret"}]}`,
+ } {
+ if _, err := validateRemoteMCPPublicConfig(json.RawMessage(raw), schema); err == nil {
+ t.Fatalf("config %s was accepted", raw)
+ }
+ }
+}
+
+func TestSelectApprovedRemoteMCPToolsFailsClosed(t *testing.T) {
+ declaration := plugincontract.RemoteMCPContribution{ToolIntent: []plugincontract.RemoteMCPToolIntent{
+ {Name: "read", Risk: "read"}, {Name: "write", Risk: "write"},
+ }}
+ discovered := []pluginruntime.RemoteMCPTool{{Name: "read"}, {Name: "undeclared"}}
+ approved, err := selectApprovedRemoteMCPTools(discovered, declaration, []string{"read"})
+ if err != nil || len(approved) != 1 || approved[0].Name != "read" {
+ t.Fatalf("approved = %#v, %v", approved, err)
+ }
+ for _, names := range [][]string{nil, {"undeclared"}, {"write"}, {"read", "read"}} {
+ if _, err := selectApprovedRemoteMCPTools(discovered, declaration, names); err == nil {
+ t.Fatalf("approval %v was accepted", names)
+ }
+ }
+}
+
+func TestSelectApprovedRemoteMCPToolsAllowsExplicitlyReviewedWildcard(t *testing.T) {
+ declaration := plugincontract.RemoteMCPContribution{ToolIntent: []plugincontract.RemoteMCPToolIntent{
+ {Name: plugincontract.RemoteMCPAnyToolIntent, Risk: "write"},
+ }}
+ discovered := []pluginruntime.RemoteMCPTool{{Name: "search-screens"}, {Name: "get-flow"}}
+ applyDeclaredRisk(discovered, declaration)
+ approved, err := selectApprovedRemoteMCPTools(discovered, declaration, []string{"search-screens"})
+ if err != nil || len(approved) != 1 || approved[0].Name != "search-screens" || approved[0].Risk != "write" {
+ t.Fatalf("approved = %#v, %v", approved, err)
+ }
+ if _, err := selectApprovedRemoteMCPTools(discovered, declaration, []string{"not-discovered"}); err == nil {
+ t.Fatal("undiscovered wildcard tool was approved")
+ }
+}
+
+func TestSecretHintDoesNotExposeShortCredential(t *testing.T) {
+ if got := secretHint("abc"); got != "••••" || strings.Contains(got, "abc") {
+ t.Fatalf("secretHint = %q", got)
+ }
+ if got := secretHint("credential"); got != "••••tial" {
+ t.Fatalf("secretHint = %q", got)
+ }
+}
+
+func TestRemoteMCPAuthHeaderRejectsProtocolAndHopByHopHeaders(t *testing.T) {
+ if !validRemoteMCPAuthHeader("X-Example-Key") {
+ t.Fatal("safe custom header was rejected")
+ }
+ for _, header := range []string{"Host", "Connection", "Content-Length", "Mcp-Session-Id", "Proxy-Authorization", "bad header"} {
+ if validRemoteMCPAuthHeader(header) {
+ t.Fatalf("unsafe header %q was accepted", header)
+ }
+ }
+}
+
+func TestSanitizeRemoteMCPReturnTo(t *testing.T) {
+ if got := sanitizeRemoteMCPReturnTo("/workspace/settings?tab=plugins"); got != "/workspace/settings?tab=plugins" {
+ t.Fatalf("safe return path changed to %q", got)
+ }
+ for _, unsafe := range []string{"https://evil.example", "//evil.example/path", "/ok\r\nLocation: https://evil.example"} {
+ if got := sanitizeRemoteMCPReturnTo(unsafe); got != "/" {
+ t.Errorf("unsafe return path %q became %q", unsafe, got)
+ }
+ }
+}
diff --git a/server/internal/service/plugin_skill.go b/server/internal/service/plugin_skill.go
new file mode 100644
index 0000000000..f33a88f806
--- /dev/null
+++ b/server/internal/service/plugin_skill.go
@@ -0,0 +1,142 @@
+package service
+
+import (
+ "fmt"
+ "path"
+ "sort"
+ "strings"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/util"
+ 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/pluginruntime"
+ "github.com/multica-ai/multica/server/pkg/skillbundle"
+)
+
+// compilePluginSkillFiles turns every artifact file owned by a Skill root into
+// an immutable execution-manifest pin. The manifest still declares only the
+// canonical SKILL.md entry; companion files are discovered by convention so a
+// community Skill directory can be packaged without translating its layout.
+func compilePluginSkillFiles(releaseID pgtype.UUID, contributionKey, entryPath string, files []db.PluginArtifactFile) ([]pluginruntime.SkillFile, []skillbundle.File, error) {
+ root, err := pluginSkillRoot(contributionKey, entryPath)
+ if err != nil {
+ return nil, nil, err
+ }
+ foundEntry := false
+ seen := make(map[string]struct{})
+ pins := make([]pluginruntime.SkillFile, 0)
+ bundleFiles := make([]skillbundle.File, 0)
+ for _, file := range files {
+ if file.ReleaseID != releaseID {
+ return nil, nil, fmt.Errorf("plugin Skill artifact file belongs to another release")
+ }
+ if file.Path == entryPath {
+ foundEntry = true
+ continue
+ }
+ if !strings.HasPrefix(file.Path, root) {
+ continue
+ }
+ relative := strings.TrimPrefix(file.Path, root)
+ if err := validatePluginSkillRelativePath(relative); err != nil {
+ return nil, nil, err
+ }
+ if _, exists := seen[relative]; exists {
+ return nil, nil, fmt.Errorf("plugin Skill contains duplicate companion path %q", relative)
+ }
+ seen[relative] = struct{}{}
+ if file.Digest != plugincontract.DigestBytes([]byte(file.Content)) || file.SizeBytes != int64(len(file.Content)) {
+ return nil, nil, fmt.Errorf("plugin Skill companion file %q failed digest validation", relative)
+ }
+ pins = append(pins, pluginruntime.SkillFile{
+ ArtifactFileID: util.UUIDToString(file.ID),
+ Path: relative,
+ Digest: file.Digest,
+ SizeBytes: file.SizeBytes,
+ })
+ bundleFiles = append(bundleFiles, skillbundle.File{Path: relative, Content: file.Content})
+ }
+ if !foundEntry {
+ return nil, nil, fmt.Errorf("plugin Skill entry %q is missing from release artifacts", entryPath)
+ }
+ sort.Slice(pins, func(i, j int) bool { return pins[i].Path < pins[j].Path })
+ sort.Slice(bundleFiles, func(i, j int) bool { return bundleFiles[i].Path < bundleFiles[j].Path })
+ return pins, bundleFiles, nil
+}
+
+func materializePinnedPluginSkill(entry pluginruntime.CompiledEntry, filesByID map[string]db.PluginArtifactFile) (AgentSkillData, error) {
+ root, err := pluginSkillRoot(entry.ContributionKey, entry.EntryPath)
+ if err != nil {
+ return AgentSkillData{}, fmt.Errorf("execution manifest contains invalid plugin Skill: %w", err)
+ }
+ releaseID, err := util.ParseUUID(entry.ReleaseID)
+ if err != nil {
+ return AgentSkillData{}, fmt.Errorf("execution manifest contains invalid release id")
+ }
+ entryFile, ok := filesByID[entry.ArtifactFileID]
+ if !ok || entryFile.ReleaseID != releaseID || entryFile.Path != entry.EntryPath || entryFile.Digest != entry.EntryDigest || plugincontract.DigestBytes([]byte(entryFile.Content)) != entry.EntryDigest {
+ return AgentSkillData{}, fmt.Errorf("pinned plugin Skill entry failed digest validation")
+ }
+ if entry.SkillFileCount != len(entry.SkillFiles) {
+ return AgentSkillData{}, fmt.Errorf("pinned plugin Skill companion file count is invalid")
+ }
+
+ skill := AgentSkillData{
+ ID: "plugin:" + entry.ContributionID,
+ Source: skillbundle.SourcePlugin,
+ Name: entry.ContributionKey,
+ Description: entry.Description,
+ Content: entryFile.Content,
+ Files: make([]AgentSkillFileData, 0, len(entry.SkillFiles)),
+ }
+ seenPaths := make(map[string]struct{}, len(entry.SkillFiles))
+ seenIDs := make(map[string]struct{}, len(entry.SkillFiles))
+ for _, pinned := range entry.SkillFiles {
+ if err := validatePluginSkillRelativePath(pinned.Path); err != nil {
+ return AgentSkillData{}, fmt.Errorf("execution manifest contains invalid plugin Skill companion file: %w", err)
+ }
+ if pinned.ArtifactFileID == "" || pinned.Digest == "" || pinned.SizeBytes < 0 {
+ return AgentSkillData{}, fmt.Errorf("execution manifest contains incomplete plugin Skill companion file")
+ }
+ if _, exists := seenPaths[pinned.Path]; exists {
+ return AgentSkillData{}, fmt.Errorf("execution manifest contains duplicate plugin Skill companion path %q", pinned.Path)
+ }
+ if _, exists := seenIDs[pinned.ArtifactFileID]; exists {
+ return AgentSkillData{}, fmt.Errorf("execution manifest contains duplicate plugin Skill artifact file id")
+ }
+ seenPaths[pinned.Path] = struct{}{}
+ seenIDs[pinned.ArtifactFileID] = struct{}{}
+
+ file, ok := filesByID[pinned.ArtifactFileID]
+ if !ok || file.ReleaseID != releaseID || file.Path != root+pinned.Path || file.Digest != pinned.Digest || file.SizeBytes != pinned.SizeBytes || plugincontract.DigestBytes([]byte(file.Content)) != pinned.Digest || int64(len(file.Content)) != pinned.SizeBytes {
+ return AgentSkillData{}, fmt.Errorf("pinned plugin Skill companion file %q failed digest validation", pinned.Path)
+ }
+ skill.Files = append(skill.Files, AgentSkillFileData{
+ Path: pinned.Path,
+ Content: file.Content,
+ SHA256: pinned.Digest,
+ SizeBytes: pinned.SizeBytes,
+ })
+ }
+ return skill, nil
+}
+
+func pluginSkillRoot(contributionKey, entryPath string) (string, error) {
+ expected := "skills/" + contributionKey + "/SKILL.md"
+ if entryPath != expected {
+ return "", fmt.Errorf("plugin Skill entry must be %q", expected)
+ }
+ return strings.TrimSuffix(expected, "SKILL.md"), nil
+}
+
+func validatePluginSkillRelativePath(relative string) error {
+ firstSegment := relative
+ if separator := strings.IndexByte(relative, '/'); separator >= 0 {
+ firstSegment = relative[:separator]
+ }
+ if relative == "" || relative == "." || relative == ".." || strings.EqualFold(firstSegment, "SKILL.md") || strings.Contains(relative, "\\") || path.IsAbs(relative) || path.Clean(relative) != relative || strings.HasPrefix(relative, "../") {
+ return fmt.Errorf("plugin Skill companion path %q is invalid", relative)
+ }
+ return nil
+}
diff --git a/server/internal/service/plugin_skill_test.go b/server/internal/service/plugin_skill_test.go
new file mode 100644
index 0000000000..37cf23a10b
--- /dev/null
+++ b/server/internal/service/plugin_skill_test.go
@@ -0,0 +1,121 @@
+package service
+
+import (
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/util"
+ 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/pluginruntime"
+)
+
+func pluginSkillArtifact(id, releaseID, path, content string) db.PluginArtifactFile {
+ return db.PluginArtifactFile{
+ ID: util.MustParseUUID(id),
+ ReleaseID: util.MustParseUUID(releaseID),
+ Path: path,
+ Digest: plugincontract.DigestBytes([]byte(content)),
+ SizeBytes: int64(len(content)),
+ Content: content,
+ }
+}
+
+func TestCompileAndMaterializePluginSkillCompanionFiles(t *testing.T) {
+ const (
+ releaseID = "11111111-1111-1111-1111-111111111111"
+ entryID = "22222222-2222-2222-2222-222222222222"
+ agentID = "33333333-3333-3333-3333-333333333333"
+ rulesID = "44444444-4444-4444-4444-444444444444"
+ )
+ entry := pluginSkillArtifact(entryID, releaseID, "skills/research/SKILL.md", "# Research")
+ agent := pluginSkillArtifact(agentID, releaseID, "skills/research/agents/openai.yaml", "interface: {}")
+ rules := pluginSkillArtifact(rulesID, releaseID, "skills/research/references/rules.md", "rules")
+ other := pluginSkillArtifact("55555555-5555-5555-5555-555555555555", releaseID, "skills/other/SKILL.md", "other")
+ license := pluginSkillArtifact("66666666-6666-6666-6666-666666666666", releaseID, "THIRD_PARTY_LICENSES/source.txt", "license")
+
+ pins, bundleFiles, err := compilePluginSkillFiles(
+ util.MustParseUUID(releaseID),
+ "research",
+ "skills/research/SKILL.md",
+ []db.PluginArtifactFile{rules, other, entry, license, agent},
+ )
+ if err != nil {
+ t.Fatalf("compilePluginSkillFiles: %v", err)
+ }
+ if len(pins) != 2 || pins[0].Path != "agents/openai.yaml" || pins[1].Path != "references/rules.md" {
+ t.Fatalf("compiled pins = %#v", pins)
+ }
+ if len(bundleFiles) != 2 || bundleFiles[0].Path != pins[0].Path || bundleFiles[1].Path != pins[1].Path {
+ t.Fatalf("bundle files = %#v", bundleFiles)
+ }
+
+ compiled := pluginruntime.CompiledEntry{
+ ReleaseID: releaseID,
+ ContributionID: "77777777-7777-7777-7777-777777777777",
+ ContributionKey: "research",
+ ArtifactFileID: entryID,
+ EntryPath: entry.Path,
+ EntryDigest: entry.Digest,
+ SkillFileCount: len(pins),
+ SkillFiles: pins,
+ Description: "Research from primary sources",
+ ContributionType: plugincontract.ContributionAgentSkillV1,
+ }
+ filesByID := map[string]db.PluginArtifactFile{
+ entryID: entry,
+ agentID: agent,
+ rulesID: rules,
+ }
+ skill, err := materializePinnedPluginSkill(compiled, filesByID)
+ if err != nil {
+ t.Fatalf("materializePinnedPluginSkill: %v", err)
+ }
+ if skill.Content != entry.Content || len(skill.Files) != 2 || skill.Files[0].Path != "agents/openai.yaml" || skill.Files[1].Path != "references/rules.md" {
+ t.Fatalf("materialized Skill = %#v", skill)
+ }
+}
+
+func TestCompilePluginSkillFilesRejectsDigestDrift(t *testing.T) {
+ const releaseID = "11111111-1111-1111-1111-111111111111"
+ entry := pluginSkillArtifact("22222222-2222-2222-2222-222222222222", releaseID, "skills/research/SKILL.md", "# Research")
+ companion := pluginSkillArtifact("33333333-3333-3333-3333-333333333333", releaseID, "skills/research/rules.md", "rules")
+ companion.Content = "tampered"
+ if _, _, err := compilePluginSkillFiles(util.MustParseUUID(releaseID), "research", entry.Path, []db.PluginArtifactFile{entry, companion}); err == nil {
+ t.Fatal("digest drift was accepted")
+ }
+}
+
+func TestMaterializePinnedPluginSkillRejectsPathEscape(t *testing.T) {
+ entryFile := pluginSkillArtifact(
+ "22222222-2222-2222-2222-222222222222",
+ "11111111-1111-1111-1111-111111111111",
+ "skills/research/SKILL.md",
+ "# Research",
+ )
+ entry := pluginruntime.CompiledEntry{
+ ReleaseID: "11111111-1111-1111-1111-111111111111",
+ ContributionKey: "research",
+ ArtifactFileID: "22222222-2222-2222-2222-222222222222",
+ EntryPath: "skills/research/SKILL.md",
+ EntryDigest: entryFile.Digest,
+ SkillFileCount: 1,
+ SkillFiles: []pluginruntime.SkillFile{{
+ ArtifactFileID: "33333333-3333-3333-3333-333333333333",
+ Path: "../escape.md",
+ Digest: "sha256:invalid",
+ SizeBytes: 1,
+ }},
+ }
+ if _, err := materializePinnedPluginSkill(entry, map[string]db.PluginArtifactFile{entry.ArtifactFileID: entryFile}); err == nil {
+ t.Fatal("path escape was accepted")
+ }
+}
+
+func TestValidatePluginSkillRelativePathRejectsPrimaryContentDescendant(t *testing.T) {
+ if err := validatePluginSkillRelativePath("SKILL.md/hidden.txt"); err == nil {
+ t.Fatal("primary content descendant was accepted")
+ }
+ if err := validatePluginSkillRelativePath(".."); err == nil {
+ t.Fatal("bare parent path was accepted")
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index a187af5b46..91e3aec423 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -3138,10 +3138,11 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
return claimed, nil
}
-// FinalizeTaskClaim atomically persists the task-scoped token and, for a
+// FinalizeTaskClaim atomically persists the task-scoped agent token, an
+// optional short-lived daemon token used by the Remote MCP broker, and, for a
// comment-backed task, the exact comment ids embedded in the response. The
// handler must call this only after the full payload has been built and before
-// writing any response bytes. A failure rolls both writes back so the claim can
+// writing any response bytes. A failure rolls every write back so the claim can
// be safely returned to the queue.
func (s *TaskService) FinalizeTaskClaim(
ctx context.Context,
@@ -3149,12 +3150,26 @@ func (s *TaskService) FinalizeTaskClaim(
token db.CreateTaskTokenParams,
deliveredCommentIDs []pgtype.UUID,
recordCommentReceipt bool,
+ daemonTokens ...db.CreateDaemonTokenParams,
) ([]pgtype.UUID, error) {
+ if len(daemonTokens) > 1 {
+ return nil, fmt.Errorf("finalize task claim: expected at most one daemon token, got %d", len(daemonTokens))
+ }
receipt := task.DeliveredCommentIds
err := s.runInTx(ctx, func(qtx *db.Queries) error {
if _, err := qtx.CreateTaskToken(ctx, token); err != nil {
return fmt.Errorf("create task token: %w", err)
}
+ if len(daemonTokens) == 1 {
+ // Opportunistic bounded cleanup keeps short-lived per-task daemon
+ // credentials from accumulating without adding another sweeper.
+ if err := qtx.DeleteExpiredDaemonTokens(ctx); err != nil {
+ return fmt.Errorf("delete expired daemon tokens: %w", err)
+ }
+ if _, err := qtx.CreateDaemonToken(ctx, daemonTokens[0]); err != nil {
+ return fmt.Errorf("create remote MCP daemon token: %w", err)
+ }
+ }
if !recordCommentReceipt {
return nil
}
@@ -4902,6 +4917,7 @@ type PluginExecutionManifestData struct {
ComposerVersion string `json:"composer_version"`
SchemaVersion int32 `json:"schema_version"`
OrderedContributions []pluginruntime.CompiledEntry `json:"ordered_contributions"`
+ Diagnostics []string `json:"diagnostics,omitempty"`
}
// LoadTaskPluginSkillBundles resolves only the immutable artifact files named
@@ -4932,35 +4948,62 @@ func (s *TaskService) LoadTaskPluginSkillBundles(ctx context.Context, taskID pgt
if len(entries) == 0 {
return nil, nil, data, nil
}
+ artifactFileIDs := make([]pgtype.UUID, 0)
+ seenArtifactFileIDs := make(map[string]struct{})
+ for _, entry := range entries {
+ if entry.ContributionType != plugincontract.ContributionAgentSkillV1 {
+ continue
+ }
+ ids := make([]string, 0, len(entry.SkillFiles)+1)
+ ids = append(ids, entry.ArtifactFileID)
+ for _, file := range entry.SkillFiles {
+ ids = append(ids, file.ArtifactFileID)
+ }
+ for _, id := range ids {
+ if _, exists := seenArtifactFileIDs[id]; exists {
+ continue
+ }
+ parsed, parseErr := util.ParseUUID(id)
+ if parseErr != nil {
+ return nil, nil, nil, fmt.Errorf("execution manifest contains invalid artifact file id")
+ }
+ seenArtifactFileIDs[id] = struct{}{}
+ artifactFileIDs = append(artifactFileIDs, parsed)
+ }
+ }
+ artifactFilesByID := make(map[string]db.PluginArtifactFile, len(artifactFileIDs))
+ if len(artifactFileIDs) > 0 {
+ artifactFiles, listErr := s.Queries.ListPluginArtifactFilesByIDs(ctx, artifactFileIDs)
+ if listErr != nil {
+ return nil, nil, nil, fmt.Errorf("load pinned plugin Skill artifacts: %w", listErr)
+ }
+ for _, file := range artifactFiles {
+ artifactFilesByID[util.UUIDToString(file.ID)] = file
+ }
+ }
skills := make([]AgentSkillData, 0, len(entries))
+ skillEntries := make([]pluginruntime.CompiledEntry, 0, len(entries))
for _, entry := range entries {
+ if entry.ContributionType == plugincontract.ContributionRemoteMCPV1 {
+ if entry.ConfigID == "" || entry.ConfigRevision <= 0 || entry.Endpoint == "" || len(entry.ApprovedTools) == 0 || entry.ToolSchemaDigest == "" {
+ return nil, nil, nil, fmt.Errorf("execution manifest contains invalid remote MCP contribution")
+ }
+ continue
+ }
if entry.ContributionType != plugincontract.ContributionAgentSkillV1 || entry.ArtifactFileID == "" {
return nil, nil, nil, fmt.Errorf("execution manifest contains unsupported plugin contribution")
}
- artifactFileID, parseErr := util.ParseUUID(entry.ArtifactFileID)
- if parseErr != nil {
- return nil, nil, nil, fmt.Errorf("execution manifest contains invalid artifact file id")
- }
- artifact, getErr := s.Queries.GetPluginArtifactFile(ctx, artifactFileID)
- if getErr != nil {
- return nil, nil, nil, fmt.Errorf("load pinned plugin artifact: %w", getErr)
+ skill, materializeErr := materializePinnedPluginSkill(entry, artifactFilesByID)
+ if materializeErr != nil {
+ return nil, nil, nil, materializeErr
}
- releaseID, parseErr := util.ParseUUID(entry.ReleaseID)
- if parseErr != nil || artifact.ReleaseID != releaseID || artifact.Path != entry.EntryPath || artifact.Digest != entry.EntryDigest || plugincontract.DigestBytes([]byte(artifact.Content)) != entry.EntryDigest {
- return nil, nil, nil, fmt.Errorf("pinned plugin artifact failed digest validation")
- }
- skills = append(skills, AgentSkillData{
- ID: "plugin:" + entry.ContributionID,
- Source: skillbundle.SourcePlugin,
- Name: entry.ContributionKey,
- Description: entry.Description,
- Content: artifact.Content,
- })
+ skills = append(skills, skill)
+ skillEntries = append(skillEntries, entry)
}
bundles, refs := BuildAgentSkillBundles(skills)
for i := range refs {
- if refs[i].Hash != entries[i].SkillBundleHash || refs[i].SizeBytes != entries[i].SkillSizeBytes || refs[i].FileCount != entries[i].SkillFileCount {
+ if refs[i].Hash != skillEntries[i].SkillBundleHash || refs[i].SizeBytes != skillEntries[i].SkillSizeBytes || refs[i].FileCount != skillEntries[i].SkillFileCount {
return nil, nil, nil, fmt.Errorf("pinned plugin skill bundle failed manifest validation")
}
}
diff --git a/server/migrations/319_remote_mcp_plugin_v1.down.sql b/server/migrations/319_remote_mcp_plugin_v1.down.sql
new file mode 100644
index 0000000000..b034b658ff
--- /dev/null
+++ b/server/migrations/319_remote_mcp_plugin_v1.down.sql
@@ -0,0 +1,10 @@
+DROP TRIGGER IF EXISTS trg_plugin_installation_config_append_only ON plugin_installation_config;
+DROP TABLE IF EXISTS plugin_installation_config;
+DROP TABLE IF EXISTS plugin_remote_mcp_secret;
+
+ALTER TABLE plugin_contribution
+ DROP CONSTRAINT IF EXISTS plugin_contribution_type_check;
+
+ALTER TABLE plugin_contribution
+ ADD CONSTRAINT plugin_contribution_type_check
+ CHECK (type IN ('agent.skill.v1'));
diff --git a/server/migrations/319_remote_mcp_plugin_v1.up.sql b/server/migrations/319_remote_mcp_plugin_v1.up.sql
new file mode 100644
index 0000000000..bed3f46c7a
--- /dev/null
+++ b/server/migrations/319_remote_mcp_plugin_v1.up.sql
@@ -0,0 +1,58 @@
+-- Remote MCP Plugin V1 adds revisioned installation configuration and a
+-- dedicated encrypted credential store. Contribution declarations remain in
+-- immutable Plugin releases; endpoint, grants, and credentials are owned by a
+-- workspace installation and never enter an artifact or execution manifest.
+
+ALTER TABLE plugin_contribution
+ DROP CONSTRAINT plugin_contribution_type_check;
+
+ALTER TABLE plugin_contribution
+ ADD CONSTRAINT plugin_contribution_type_check
+ CHECK (type IN ('agent.skill.v1', 'tool.remote-mcp.v1'));
+
+CREATE TABLE plugin_remote_mcp_secret (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ installation_id UUID NOT NULL,
+ contribution_id UUID NOT NULL,
+ version BIGINT NOT NULL CHECK (version > 0),
+ ciphertext BYTEA NOT NULL CHECK (octet_length(ciphertext) > 0),
+ hint TEXT NOT NULL DEFAULT '' CHECK (char_length(hint) <= 32),
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'revoked')),
+ created_by UUID,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ revoked_at TIMESTAMPTZ,
+ CHECK (
+ (status = 'active' AND revoked_at IS NULL)
+ OR (status = 'revoked' AND revoked_at IS NOT NULL)
+ )
+);
+
+CREATE TABLE plugin_installation_config (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ installation_id UUID NOT NULL,
+ contribution_id UUID NOT NULL,
+ revision BIGINT NOT NULL CHECK (revision > 0),
+ endpoint TEXT NOT NULL CHECK (char_length(endpoint) BETWEEN 9 AND 2048),
+ public_config JSONB NOT NULL DEFAULT '{}'::jsonb CHECK (jsonb_typeof(public_config) = 'object'),
+ auth_type TEXT NOT NULL CHECK (auth_type IN ('none', 'bearer', 'header')),
+ auth_header TEXT NOT NULL DEFAULT '' CHECK (char_length(auth_header) <= 128),
+ secret_ref UUID,
+ approved_tools JSONB NOT NULL DEFAULT '[]'::jsonb CHECK (jsonb_typeof(approved_tools) = 'array'),
+ schema_digest TEXT,
+ failure_policy TEXT NOT NULL DEFAULT 'required' CHECK (failure_policy IN ('required', 'optional')),
+ reviewed_by UUID,
+ reviewed_at TIMESTAMPTZ,
+ created_by UUID,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CHECK ((auth_type = 'none') = (secret_ref IS NULL)),
+ CHECK (auth_type <> 'header' OR char_length(auth_header) > 0),
+ CHECK ((jsonb_array_length(approved_tools) = 0) = (schema_digest IS NULL)),
+ CHECK (schema_digest IS NULL OR schema_digest ~ '^sha256:[0-9a-f]{64}$'),
+ CHECK ((reviewed_by IS NULL) = (reviewed_at IS NULL))
+);
+
+CREATE TRIGGER trg_plugin_installation_config_append_only
+BEFORE UPDATE ON plugin_installation_config
+FOR EACH ROW EXECUTE FUNCTION reject_plugin_append_only_update();
diff --git a/server/migrations/320_plugin_installation_config_revision_index.down.sql b/server/migrations/320_plugin_installation_config_revision_index.down.sql
new file mode 100644
index 0000000000..e4f869c7d1
--- /dev/null
+++ b/server/migrations/320_plugin_installation_config_revision_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_installation_config_contribution_revision;
diff --git a/server/migrations/320_plugin_installation_config_revision_index.up.sql b/server/migrations/320_plugin_installation_config_revision_index.up.sql
new file mode 100644
index 0000000000..467843140c
--- /dev/null
+++ b/server/migrations/320_plugin_installation_config_revision_index.up.sql
@@ -0,0 +1,2 @@
+CREATE UNIQUE INDEX CONCURRENTLY idx_plugin_installation_config_contribution_revision
+ ON plugin_installation_config (installation_id, contribution_id, revision);
diff --git a/server/migrations/321_plugin_installation_config_workspace_index.down.sql b/server/migrations/321_plugin_installation_config_workspace_index.down.sql
new file mode 100644
index 0000000000..a588aff6a0
--- /dev/null
+++ b/server/migrations/321_plugin_installation_config_workspace_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_installation_config_workspace;
diff --git a/server/migrations/321_plugin_installation_config_workspace_index.up.sql b/server/migrations/321_plugin_installation_config_workspace_index.up.sql
new file mode 100644
index 0000000000..b15aaad0f3
--- /dev/null
+++ b/server/migrations/321_plugin_installation_config_workspace_index.up.sql
@@ -0,0 +1,2 @@
+CREATE INDEX CONCURRENTLY idx_plugin_installation_config_workspace
+ ON plugin_installation_config (workspace_id, installation_id, contribution_id, revision DESC);
diff --git a/server/migrations/322_plugin_remote_mcp_secret_revision_index.down.sql b/server/migrations/322_plugin_remote_mcp_secret_revision_index.down.sql
new file mode 100644
index 0000000000..67d5ddd1d7
--- /dev/null
+++ b/server/migrations/322_plugin_remote_mcp_secret_revision_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_remote_mcp_secret_revision;
diff --git a/server/migrations/322_plugin_remote_mcp_secret_revision_index.up.sql b/server/migrations/322_plugin_remote_mcp_secret_revision_index.up.sql
new file mode 100644
index 0000000000..1c3215ba52
--- /dev/null
+++ b/server/migrations/322_plugin_remote_mcp_secret_revision_index.up.sql
@@ -0,0 +1,2 @@
+CREATE UNIQUE INDEX CONCURRENTLY idx_plugin_remote_mcp_secret_revision
+ ON plugin_remote_mcp_secret (installation_id, contribution_id, version);
diff --git a/server/migrations/323_plugin_remote_mcp_secret_workspace_index.down.sql b/server/migrations/323_plugin_remote_mcp_secret_workspace_index.down.sql
new file mode 100644
index 0000000000..207be693b4
--- /dev/null
+++ b/server/migrations/323_plugin_remote_mcp_secret_workspace_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_remote_mcp_secret_workspace;
diff --git a/server/migrations/323_plugin_remote_mcp_secret_workspace_index.up.sql b/server/migrations/323_plugin_remote_mcp_secret_workspace_index.up.sql
new file mode 100644
index 0000000000..48cd99f21f
--- /dev/null
+++ b/server/migrations/323_plugin_remote_mcp_secret_workspace_index.up.sql
@@ -0,0 +1,2 @@
+CREATE INDEX CONCURRENTLY idx_plugin_remote_mcp_secret_workspace
+ ON plugin_remote_mcp_secret (workspace_id, installation_id, contribution_id, version DESC);
diff --git a/server/migrations/324_plugin_remote_mcp_one_active_secret_index.down.sql b/server/migrations/324_plugin_remote_mcp_one_active_secret_index.down.sql
new file mode 100644
index 0000000000..c700b232e3
--- /dev/null
+++ b/server/migrations/324_plugin_remote_mcp_one_active_secret_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_plugin_remote_mcp_one_active_secret;
diff --git a/server/migrations/324_plugin_remote_mcp_one_active_secret_index.up.sql b/server/migrations/324_plugin_remote_mcp_one_active_secret_index.up.sql
new file mode 100644
index 0000000000..f5ed10fb4c
--- /dev/null
+++ b/server/migrations/324_plugin_remote_mcp_one_active_secret_index.up.sql
@@ -0,0 +1,3 @@
+CREATE UNIQUE INDEX CONCURRENTLY idx_plugin_remote_mcp_one_active_secret
+ ON plugin_remote_mcp_secret (installation_id, contribution_id)
+ WHERE status = 'active';
diff --git a/server/migrations/325_plugin_remote_mcp_oauth.down.sql b/server/migrations/325_plugin_remote_mcp_oauth.down.sql
new file mode 100644
index 0000000000..ffb9a7dc9c
--- /dev/null
+++ b/server/migrations/325_plugin_remote_mcp_oauth.down.sql
@@ -0,0 +1,18 @@
+DROP TABLE IF EXISTS plugin_remote_mcp_oauth_state;
+
+DELETE FROM plugin_remote_mcp_secret
+WHERE id IN (SELECT secret_ref FROM plugin_installation_config WHERE auth_type = 'oauth');
+
+DELETE FROM plugin_installation_config WHERE auth_type = 'oauth';
+
+ALTER TABLE plugin_installation_config
+ DROP CONSTRAINT IF EXISTS plugin_installation_config_discovered_digest_check,
+ DROP COLUMN IF EXISTS discovered_schema_digest,
+ DROP COLUMN IF EXISTS discovered_tools;
+
+ALTER TABLE plugin_installation_config
+ DROP CONSTRAINT plugin_installation_config_auth_type_check;
+
+ALTER TABLE plugin_installation_config
+ ADD CONSTRAINT plugin_installation_config_auth_type_check
+ CHECK (auth_type IN ('none', 'bearer', 'header'));
diff --git a/server/migrations/325_plugin_remote_mcp_oauth.up.sql b/server/migrations/325_plugin_remote_mcp_oauth.up.sql
new file mode 100644
index 0000000000..c5a9aa828f
--- /dev/null
+++ b/server/migrations/325_plugin_remote_mcp_oauth.up.sql
@@ -0,0 +1,40 @@
+-- Add first-class OAuth 2.1 connections for hosted Remote MCP servers.
+-- Authorization state is short-lived and single-use. Access/refresh tokens,
+-- PKCE verifiers, and optional client secrets are always secretbox ciphertext.
+
+ALTER TABLE plugin_installation_config
+ DROP CONSTRAINT plugin_installation_config_auth_type_check;
+
+ALTER TABLE plugin_installation_config
+ ADD CONSTRAINT plugin_installation_config_auth_type_check
+ CHECK (auth_type IN ('none', 'bearer', 'header', 'oauth'));
+
+ALTER TABLE plugin_installation_config
+ ADD COLUMN discovered_tools JSONB NOT NULL DEFAULT '[]'::jsonb
+ CHECK (jsonb_typeof(discovered_tools) = 'array'),
+ ADD COLUMN discovered_schema_digest TEXT
+ CHECK (discovered_schema_digest IS NULL OR discovered_schema_digest ~ '^sha256:[0-9a-f]{64}$'),
+ ADD CONSTRAINT plugin_installation_config_discovered_digest_check
+ CHECK ((jsonb_array_length(discovered_tools) = 0) = (discovered_schema_digest IS NULL));
+
+CREATE TABLE plugin_remote_mcp_oauth_state (
+ state_hash BYTEA PRIMARY KEY CHECK (octet_length(state_hash) = 32),
+ workspace_id UUID NOT NULL,
+ installation_id UUID NOT NULL,
+ contribution_id UUID NOT NULL,
+ actor_id UUID NOT NULL,
+ endpoint TEXT NOT NULL CHECK (char_length(endpoint) BETWEEN 9 AND 2048),
+ public_config JSONB NOT NULL DEFAULT '{}'::jsonb CHECK (jsonb_typeof(public_config) = 'object'),
+ failure_policy TEXT NOT NULL DEFAULT 'required' CHECK (failure_policy IN ('required', 'optional')),
+ authorization_endpoint TEXT NOT NULL CHECK (char_length(authorization_endpoint) BETWEEN 9 AND 2048),
+ token_endpoint TEXT NOT NULL CHECK (char_length(token_endpoint) BETWEEN 9 AND 2048),
+ client_id TEXT NOT NULL CHECK (char_length(client_id) BETWEEN 1 AND 2048),
+ scope TEXT NOT NULL DEFAULT '' CHECK (char_length(scope) <= 4096),
+ redirect_uri TEXT NOT NULL CHECK (char_length(redirect_uri) BETWEEN 9 AND 2048),
+ return_to TEXT NOT NULL DEFAULT '' CHECK (char_length(return_to) <= 2048),
+ secret_ciphertext BYTEA NOT NULL CHECK (octet_length(secret_ciphertext) > 0),
+ expires_at TIMESTAMPTZ NOT NULL,
+ consumed_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CHECK (expires_at > created_at)
+);
diff --git a/server/migrations/326_plugin_remote_mcp_oauth_state_expiry_index.down.sql b/server/migrations/326_plugin_remote_mcp_oauth_state_expiry_index.down.sql
new file mode 100644
index 0000000000..0721e031ea
--- /dev/null
+++ b/server/migrations/326_plugin_remote_mcp_oauth_state_expiry_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS plugin_remote_mcp_oauth_state_expiry_idx;
diff --git a/server/migrations/326_plugin_remote_mcp_oauth_state_expiry_index.up.sql b/server/migrations/326_plugin_remote_mcp_oauth_state_expiry_index.up.sql
new file mode 100644
index 0000000000..360bea79e6
--- /dev/null
+++ b/server/migrations/326_plugin_remote_mcp_oauth_state_expiry_index.up.sql
@@ -0,0 +1,2 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS plugin_remote_mcp_oauth_state_expiry_idx
+ ON plugin_remote_mcp_oauth_state (expires_at);
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index d640467ce5..d6db518f26 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -2908,6 +2908,50 @@ func codexPatchResultOutput(status string, changes []any, stdout, stderr string)
return strings.Join(segments, "\n")
}
+// codexMCPToolInput keeps the remote server visible in the transcript while
+// preserving the provider-native argument shape under a stable key. Redact at
+// the adapter boundary as well as in the daemon: other Message consumers must
+// not have to know that an MCP invocation can carry credentials or private
+// query text in deeply nested arguments.
+func codexMCPToolInput(item map[string]any) map[string]any {
+ input := make(map[string]any, 2)
+ if server, _ := item["server"].(string); strings.TrimSpace(server) != "" {
+ input["server"] = server
+ }
+ if arguments, ok := item["arguments"]; ok {
+ input["arguments"] = arguments
+ }
+ return redact.InputMap(input)
+}
+
+func codexMCPToolName(item map[string]any) string {
+ if tool, _ := item["tool"].(string); strings.TrimSpace(tool) != "" {
+ return tool
+ }
+ return "mcp_tool"
+}
+
+// codexMCPToolResultOutput deliberately excludes result.content and
+// structuredContent. Those values can be large and may contain private data;
+// the Agent Log needs an auditable outcome, not a second copy of the provider
+// payload that Codex already consumed.
+func codexMCPToolResultOutput(item map[string]any) string {
+ status, _ := item["status"].(string)
+ status = codexNormalizePatchStatus(status)
+ if status == "" {
+ status = "completed"
+ }
+
+ segments := []string{status}
+ if durationMS := codexInt64(item, "durationMs", "duration_ms"); durationMS > 0 {
+ segments = append(segments, fmt.Sprintf("duration: %d ms", durationMS))
+ }
+ if errMessage := extractNestedString(item, "error", "message"); strings.TrimSpace(errMessage) != "" {
+ segments = append(segments, "error: "+sanitizeCodexDiagnostic(errMessage))
+ }
+ return strings.Join(segments, "\n")
+}
+
func codexPatchHeadline(status string, fileCount int) string {
switch {
case status == "" && fileCount == 0:
@@ -3175,6 +3219,28 @@ func (c *codexClient) handleItemNotification(method string, params map[string]an
})
}
+ case method == "item/started" && itemType == "mcpToolCall":
+ if c.onMessage != nil {
+ c.onMessage(Message{
+ Type: MessageToolUse,
+ Tool: codexMCPToolName(item),
+ CallID: itemID,
+ Input: codexMCPToolInput(item),
+ })
+ }
+
+ case method == "item/completed" && itemType == "mcpToolCall":
+ status, _ := item["status"].(string)
+ if c.onMessage != nil {
+ c.onMessage(Message{
+ Type: MessageToolResult,
+ Tool: codexMCPToolName(item),
+ CallID: itemID,
+ Output: codexMCPToolResultOutput(item),
+ Status: codexNormalizePatchStatus(status),
+ })
+ }
+
case method == "item/completed" && itemType == "agentMessage":
text, _ := item["text"].(string)
if text != "" && c.onMessage != nil {
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index 840d55702b..9c8f6e51c7 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -1230,6 +1230,71 @@ func TestCodexRawItemCommandExecution(t *testing.T) {
}
}
+func TestCodexRawItemMCPToolCall(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+
+ var messages []Message
+ c.onMessage = func(msg Message) {
+ messages = append(messages, msg)
+ }
+
+ c.handleLine(`{"jsonrpc":"2.0","method":"item/started","params":{"item":{"type":"mcpToolCall","id":"mcp-1","server":"plugin-exa-search","tool":"web_search_exa","arguments":{"query":"latest Multica news","credentials":{"api_key":"sk-12345678901234567890"}},"status":"inProgress"}}}`)
+ c.handleLine(`{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"mcpToolCall","id":"mcp-1","server":"plugin-exa-search","tool":"web_search_exa","arguments":{"query":"latest Multica news"},"status":"completed","durationMs":1429,"result":{"content":[{"type":"text","text":"private provider payload"}]}}}}`)
+
+ if len(messages) != 2 {
+ t.Fatalf("expected 2 messages, got %d", len(messages))
+ }
+
+ begin := messages[0]
+ if begin.Type != MessageToolUse || begin.Tool != "web_search_exa" || begin.CallID != "mcp-1" {
+ t.Fatalf("unexpected start message: %+v", begin)
+ }
+ if begin.Input["server"] != "plugin-exa-search" {
+ t.Fatalf("expected MCP server provenance, got %#v", begin.Input)
+ }
+ arguments, ok := begin.Input["arguments"].(map[string]any)
+ if !ok || arguments["query"] != "latest Multica news" {
+ t.Fatalf("expected MCP arguments, got %#v", begin.Input["arguments"])
+ }
+ credentials, ok := arguments["credentials"].(map[string]any)
+ if !ok || credentials["api_key"] != "[REDACTED API KEY]" {
+ t.Fatalf("expected nested MCP secret to be redacted, got %#v", arguments["credentials"])
+ }
+
+ end := messages[1]
+ if end.Type != MessageToolResult || end.Tool != "web_search_exa" || end.CallID != "mcp-1" || end.Status != "completed" {
+ t.Fatalf("unexpected complete message: %+v", end)
+ }
+ if end.Output != "completed\nduration: 1429 ms" {
+ t.Fatalf("unexpected MCP result summary: %q", end.Output)
+ }
+ if strings.Contains(end.Output, "private provider payload") {
+ t.Fatalf("MCP result content leaked into transcript summary: %q", end.Output)
+ }
+}
+
+func TestCodexRawItemMCPToolCallFailureIsSanitized(t *testing.T) {
+ t.Parallel()
+
+ c, _, _ := newTestCodexClient(t)
+ c.notificationProtocol = "raw"
+
+ var messages []Message
+ c.onMessage = func(msg Message) { messages = append(messages, msg) }
+
+ c.handleLine(`{"jsonrpc":"2.0","method":"item/completed","params":{"item":{"type":"mcpToolCall","id":"mcp-2","server":"plugin-exa-search","tool":"web_search_exa","status":"failed","error":{"message":"Bearer secret-token-value"}}}}`)
+
+ if len(messages) != 1 {
+ t.Fatalf("expected 1 message, got %d", len(messages))
+ }
+ if got := messages[0].Output; got != "failed\nerror: Bearer [REDACTED]" {
+ t.Fatalf("unexpected sanitized MCP failure summary: %q", got)
+ }
+}
+
func TestCodexRawItemAgentMessageFinalAnswer(t *testing.T) {
t.Parallel()
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 4dc8d3f1ec..5640840096 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -1019,6 +1019,28 @@ type PluginInstallation struct {
UninstalledAt pgtype.Timestamptz `json:"uninstalled_at"`
}
+type PluginInstallationConfig struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ContributionID pgtype.UUID `json:"contribution_id"`
+ Revision int64 `json:"revision"`
+ Endpoint string `json:"endpoint"`
+ PublicConfig []byte `json:"public_config"`
+ AuthType string `json:"auth_type"`
+ AuthHeader string `json:"auth_header"`
+ SecretRef pgtype.UUID `json:"secret_ref"`
+ ApprovedTools []byte `json:"approved_tools"`
+ SchemaDigest pgtype.Text `json:"schema_digest"`
+ FailurePolicy string `json:"failure_policy"`
+ ReviewedBy pgtype.UUID `json:"reviewed_by"`
+ ReviewedAt pgtype.Timestamptz `json:"reviewed_at"`
+ CreatedBy pgtype.UUID `json:"created_by"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ DiscoveredTools []byte `json:"discovered_tools"`
+ DiscoveredSchemaDigest pgtype.Text `json:"discovered_schema_digest"`
+}
+
type PluginRelease struct {
ID pgtype.UUID `json:"id"`
PluginID pgtype.UUID `json:"plugin_id"`
@@ -1039,6 +1061,41 @@ type PluginRelease struct {
PublishedAt pgtype.Timestamptz `json:"published_at"`
}
+type PluginRemoteMcpOauthState struct {
+ StateHash []byte `json:"state_hash"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ContributionID pgtype.UUID `json:"contribution_id"`
+ ActorID pgtype.UUID `json:"actor_id"`
+ Endpoint string `json:"endpoint"`
+ PublicConfig []byte `json:"public_config"`
+ FailurePolicy string `json:"failure_policy"`
+ AuthorizationEndpoint string `json:"authorization_endpoint"`
+ TokenEndpoint string `json:"token_endpoint"`
+ ClientID string `json:"client_id"`
+ Scope string `json:"scope"`
+ RedirectUri string `json:"redirect_uri"`
+ ReturnTo string `json:"return_to"`
+ SecretCiphertext []byte `json:"secret_ciphertext"`
+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`
+ ConsumedAt pgtype.Timestamptz `json:"consumed_at"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
+type PluginRemoteMcpSecret struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ContributionID pgtype.UUID `json:"contribution_id"`
+ Version int64 `json:"version"`
+ Ciphertext []byte `json:"ciphertext"`
+ Hint string `json:"hint"`
+ Status string `json:"status"`
+ CreatedBy pgtype.UUID `json:"created_by"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ RevokedAt pgtype.Timestamptz `json:"revoked_at"`
+}
+
type PluginWorkspaceCapabilityState struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
NextRevision int64 `json:"next_revision"`
diff --git a/server/pkg/db/generated/plugin.sql.go b/server/pkg/db/generated/plugin.sql.go
index 4fb29f33c0..2b9467a0ee 100644
--- a/server/pkg/db/generated/plugin.sql.go
+++ b/server/pkg/db/generated/plugin.sql.go
@@ -96,6 +96,41 @@ func (q *Queries) ActivatePluginWorkspaceCapabilitySnapshot(ctx context.Context,
return i, err
}
+const claimPluginRemoteMCPOAuthState = `-- name: ClaimPluginRemoteMCPOAuthState :one
+UPDATE plugin_remote_mcp_oauth_state
+SET consumed_at = now()
+WHERE state_hash = $1
+ AND consumed_at IS NULL
+ AND expires_at > now()
+RETURNING state_hash, workspace_id, installation_id, contribution_id, actor_id, endpoint, public_config, failure_policy, authorization_endpoint, token_endpoint, client_id, scope, redirect_uri, return_to, secret_ciphertext, expires_at, consumed_at, created_at
+`
+
+func (q *Queries) ClaimPluginRemoteMCPOAuthState(ctx context.Context, stateHash []byte) (PluginRemoteMcpOauthState, error) {
+ row := q.db.QueryRow(ctx, claimPluginRemoteMCPOAuthState, stateHash)
+ var i PluginRemoteMcpOauthState
+ err := row.Scan(
+ &i.StateHash,
+ &i.WorkspaceID,
+ &i.InstallationID,
+ &i.ContributionID,
+ &i.ActorID,
+ &i.Endpoint,
+ &i.PublicConfig,
+ &i.FailurePolicy,
+ &i.AuthorizationEndpoint,
+ &i.TokenEndpoint,
+ &i.ClientID,
+ &i.Scope,
+ &i.RedirectUri,
+ &i.ReturnTo,
+ &i.SecretCiphertext,
+ &i.ExpiresAt,
+ &i.ConsumedAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
const createPluginArtifactFile = `-- name: CreatePluginArtifactFile :one
WITH parent AS MATERIALIZED (
SELECT plugin_release.id
@@ -558,6 +593,120 @@ func (q *Queries) CreatePluginInstallation(ctx context.Context, arg CreatePlugin
return i, err
}
+const createPluginInstallationConfig = `-- name: CreatePluginInstallationConfig :one
+WITH parent AS MATERIALIZED (
+ SELECT installation.id, contribution.id AS contribution_id
+ FROM plugin_installation installation
+ JOIN plugin_release release
+ ON release.id = installation.desired_release_id
+ AND release.plugin_id = installation.plugin_id
+ AND release.revocation_status = 'active'
+ JOIN plugin_contribution contribution
+ ON contribution.release_id = release.id
+ AND contribution.id = $14
+ AND contribution.type = 'tool.remote-mcp.v1'
+ WHERE installation.id = $15
+ AND installation.workspace_id = $1
+ AND installation.uninstalled_at IS NULL
+ AND (
+ ($4::text = 'none' AND $6::uuid IS NULL)
+ OR EXISTS (
+ SELECT 1 FROM plugin_remote_mcp_secret secret
+ WHERE secret.id = $6::uuid
+ AND secret.workspace_id = $1
+ AND secret.installation_id = installation.id
+ AND secret.contribution_id = contribution.id
+ AND secret.status = 'active'
+ )
+ )
+ FOR UPDATE OF installation
+ FOR KEY SHARE OF release, contribution
+), next_revision AS (
+ SELECT COALESCE(MAX(revision), 0) + 1 AS revision
+ FROM plugin_installation_config
+ WHERE installation_id = $15
+ AND contribution_id = $14
+)
+INSERT INTO plugin_installation_config (
+ workspace_id, installation_id, contribution_id, revision,
+ endpoint, public_config, auth_type, auth_header, secret_ref,
+ discovered_tools, discovered_schema_digest,
+ approved_tools, schema_digest, failure_policy,
+ reviewed_by, reviewed_at, created_by
+)
+SELECT
+ $1, parent.id, parent.contribution_id, next_revision.revision,
+ $2, $3, $4, $5, $6,
+ $7, $8,
+ $9, $10, $11,
+ $12,
+ CASE WHEN $12::uuid IS NULL THEN NULL ELSE now() END,
+ $13
+FROM parent, next_revision
+RETURNING id, workspace_id, installation_id, contribution_id, revision, endpoint, public_config, auth_type, auth_header, secret_ref, approved_tools, schema_digest, failure_policy, reviewed_by, reviewed_at, created_by, created_at, discovered_tools, discovered_schema_digest
+`
+
+type CreatePluginInstallationConfigParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Endpoint string `json:"endpoint"`
+ PublicConfig []byte `json:"public_config"`
+ AuthType string `json:"auth_type"`
+ AuthHeader string `json:"auth_header"`
+ SecretRef pgtype.UUID `json:"secret_ref"`
+ DiscoveredTools []byte `json:"discovered_tools"`
+ DiscoveredSchemaDigest pgtype.Text `json:"discovered_schema_digest"`
+ ApprovedTools []byte `json:"approved_tools"`
+ SchemaDigest pgtype.Text `json:"schema_digest"`
+ FailurePolicy string `json:"failure_policy"`
+ ReviewedBy pgtype.UUID `json:"reviewed_by"`
+ CreatedBy pgtype.UUID `json:"created_by"`
+ ContributionID pgtype.UUID `json:"contribution_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+}
+
+func (q *Queries) CreatePluginInstallationConfig(ctx context.Context, arg CreatePluginInstallationConfigParams) (PluginInstallationConfig, error) {
+ row := q.db.QueryRow(ctx, createPluginInstallationConfig,
+ arg.WorkspaceID,
+ arg.Endpoint,
+ arg.PublicConfig,
+ arg.AuthType,
+ arg.AuthHeader,
+ arg.SecretRef,
+ arg.DiscoveredTools,
+ arg.DiscoveredSchemaDigest,
+ arg.ApprovedTools,
+ arg.SchemaDigest,
+ arg.FailurePolicy,
+ arg.ReviewedBy,
+ arg.CreatedBy,
+ arg.ContributionID,
+ arg.InstallationID,
+ )
+ var i PluginInstallationConfig
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.InstallationID,
+ &i.ContributionID,
+ &i.Revision,
+ &i.Endpoint,
+ &i.PublicConfig,
+ &i.AuthType,
+ &i.AuthHeader,
+ &i.SecretRef,
+ &i.ApprovedTools,
+ &i.SchemaDigest,
+ &i.FailurePolicy,
+ &i.ReviewedBy,
+ &i.ReviewedAt,
+ &i.CreatedBy,
+ &i.CreatedAt,
+ &i.DiscoveredTools,
+ &i.DiscoveredSchemaDigest,
+ )
+ return i, err
+}
+
const createPluginRelease = `-- name: CreatePluginRelease :one
WITH parent AS MATERIALIZED (
SELECT plugin_identity.id
@@ -633,6 +782,165 @@ func (q *Queries) CreatePluginRelease(ctx context.Context, arg CreatePluginRelea
return i, err
}
+const createPluginRemoteMCPOAuthState = `-- name: CreatePluginRemoteMCPOAuthState :one
+INSERT INTO plugin_remote_mcp_oauth_state (
+ state_hash, workspace_id, installation_id, contribution_id, actor_id,
+ endpoint, public_config, failure_policy,
+ authorization_endpoint, token_endpoint, client_id, scope,
+ redirect_uri, return_to, secret_ciphertext, expires_at
+) VALUES (
+ $1, $2, $3, $4, $5,
+ $6, $7, $8,
+ $9, $10, $11, $12,
+ $13, $14, $15, $16
+)
+RETURNING state_hash, workspace_id, installation_id, contribution_id, actor_id, endpoint, public_config, failure_policy, authorization_endpoint, token_endpoint, client_id, scope, redirect_uri, return_to, secret_ciphertext, expires_at, consumed_at, created_at
+`
+
+type CreatePluginRemoteMCPOAuthStateParams struct {
+ StateHash []byte `json:"state_hash"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ContributionID pgtype.UUID `json:"contribution_id"`
+ ActorID pgtype.UUID `json:"actor_id"`
+ Endpoint string `json:"endpoint"`
+ PublicConfig []byte `json:"public_config"`
+ FailurePolicy string `json:"failure_policy"`
+ AuthorizationEndpoint string `json:"authorization_endpoint"`
+ TokenEndpoint string `json:"token_endpoint"`
+ ClientID string `json:"client_id"`
+ Scope string `json:"scope"`
+ RedirectUri string `json:"redirect_uri"`
+ ReturnTo string `json:"return_to"`
+ SecretCiphertext []byte `json:"secret_ciphertext"`
+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`
+}
+
+func (q *Queries) CreatePluginRemoteMCPOAuthState(ctx context.Context, arg CreatePluginRemoteMCPOAuthStateParams) (PluginRemoteMcpOauthState, error) {
+ row := q.db.QueryRow(ctx, createPluginRemoteMCPOAuthState,
+ arg.StateHash,
+ arg.WorkspaceID,
+ arg.InstallationID,
+ arg.ContributionID,
+ arg.ActorID,
+ arg.Endpoint,
+ arg.PublicConfig,
+ arg.FailurePolicy,
+ arg.AuthorizationEndpoint,
+ arg.TokenEndpoint,
+ arg.ClientID,
+ arg.Scope,
+ arg.RedirectUri,
+ arg.ReturnTo,
+ arg.SecretCiphertext,
+ arg.ExpiresAt,
+ )
+ var i PluginRemoteMcpOauthState
+ err := row.Scan(
+ &i.StateHash,
+ &i.WorkspaceID,
+ &i.InstallationID,
+ &i.ContributionID,
+ &i.ActorID,
+ &i.Endpoint,
+ &i.PublicConfig,
+ &i.FailurePolicy,
+ &i.AuthorizationEndpoint,
+ &i.TokenEndpoint,
+ &i.ClientID,
+ &i.Scope,
+ &i.RedirectUri,
+ &i.ReturnTo,
+ &i.SecretCiphertext,
+ &i.ExpiresAt,
+ &i.ConsumedAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
+const createPluginRemoteMCPSecret = `-- name: CreatePluginRemoteMCPSecret :one
+WITH parent AS MATERIALIZED (
+ SELECT installation.id, contribution.id AS contribution_id
+ FROM plugin_installation installation
+ JOIN plugin_release release
+ ON release.id = installation.desired_release_id
+ AND release.plugin_id = installation.plugin_id
+ AND release.revocation_status = 'active'
+ JOIN plugin_contribution contribution
+ ON contribution.release_id = release.id
+ AND contribution.id = $5
+ AND contribution.type = 'tool.remote-mcp.v1'
+ WHERE installation.id = $6
+ AND installation.workspace_id = $1
+ AND installation.uninstalled_at IS NULL
+ FOR UPDATE OF installation
+ FOR KEY SHARE OF release, contribution
+), next_version AS (
+ SELECT COALESCE(MAX(version), 0) + 1 AS version
+ FROM plugin_remote_mcp_secret
+ WHERE installation_id = $6
+ AND contribution_id = $5
+)
+INSERT INTO plugin_remote_mcp_secret (
+ workspace_id, installation_id, contribution_id, version,
+ ciphertext, hint, created_by
+)
+SELECT
+ $1, parent.id, parent.contribution_id, next_version.version,
+ $2, $3, $4
+FROM parent, next_version
+RETURNING id, workspace_id, installation_id, contribution_id, version, ciphertext, hint, status, created_by, created_at, revoked_at
+`
+
+type CreatePluginRemoteMCPSecretParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Ciphertext []byte `json:"ciphertext"`
+ Hint string `json:"hint"`
+ CreatedBy pgtype.UUID `json:"created_by"`
+ ContributionID pgtype.UUID `json:"contribution_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+}
+
+func (q *Queries) CreatePluginRemoteMCPSecret(ctx context.Context, arg CreatePluginRemoteMCPSecretParams) (PluginRemoteMcpSecret, error) {
+ row := q.db.QueryRow(ctx, createPluginRemoteMCPSecret,
+ arg.WorkspaceID,
+ arg.Ciphertext,
+ arg.Hint,
+ arg.CreatedBy,
+ arg.ContributionID,
+ arg.InstallationID,
+ )
+ var i PluginRemoteMcpSecret
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.InstallationID,
+ &i.ContributionID,
+ &i.Version,
+ &i.Ciphertext,
+ &i.Hint,
+ &i.Status,
+ &i.CreatedBy,
+ &i.CreatedAt,
+ &i.RevokedAt,
+ )
+ return i, err
+}
+
+const deleteExpiredPluginRemoteMCPOAuthStates = `-- name: DeleteExpiredPluginRemoteMCPOAuthStates :execrows
+DELETE FROM plugin_remote_mcp_oauth_state
+WHERE expires_at <= now() OR consumed_at < now() - interval '1 hour'
+`
+
+func (q *Queries) DeleteExpiredPluginRemoteMCPOAuthStates(ctx context.Context) (int64, error) {
+ result, err := q.db.Exec(ctx, deleteExpiredPluginRemoteMCPOAuthStates)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const ensurePluginWorkspaceCapabilityState = `-- name: EnsurePluginWorkspaceCapabilityState :one
WITH workspace_guard AS MATERIALIZED (
SELECT workspace.id
@@ -660,6 +968,251 @@ func (q *Queries) EnsurePluginWorkspaceCapabilityState(ctx context.Context, work
return i, err
}
+const getActivePluginRemoteMCPSecret = `-- name: GetActivePluginRemoteMCPSecret :one
+SELECT id, workspace_id, installation_id, contribution_id, version, ciphertext, hint, status, created_by, created_at, revoked_at FROM plugin_remote_mcp_secret
+WHERE id = $1
+ AND workspace_id = $2
+ AND installation_id = $3
+ AND contribution_id = $4
+ AND status = 'active'
+`
+
+type GetActivePluginRemoteMCPSecretParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ContributionID pgtype.UUID `json:"contribution_id"`
+}
+
+func (q *Queries) GetActivePluginRemoteMCPSecret(ctx context.Context, arg GetActivePluginRemoteMCPSecretParams) (PluginRemoteMcpSecret, error) {
+ row := q.db.QueryRow(ctx, getActivePluginRemoteMCPSecret,
+ arg.ID,
+ arg.WorkspaceID,
+ arg.InstallationID,
+ arg.ContributionID,
+ )
+ var i PluginRemoteMcpSecret
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.InstallationID,
+ &i.ContributionID,
+ &i.Version,
+ &i.Ciphertext,
+ &i.Hint,
+ &i.Status,
+ &i.CreatedBy,
+ &i.CreatedAt,
+ &i.RevokedAt,
+ )
+ return i, err
+}
+
+const getActivePluginRemoteMCPSecretForUpdate = `-- name: GetActivePluginRemoteMCPSecretForUpdate :one
+SELECT id, workspace_id, installation_id, contribution_id, version, ciphertext, hint, status, created_by, created_at, revoked_at FROM plugin_remote_mcp_secret
+WHERE id = $1
+ AND workspace_id = $2
+ AND installation_id = $3
+ AND contribution_id = $4
+ AND status = 'active'
+FOR UPDATE
+`
+
+type GetActivePluginRemoteMCPSecretForUpdateParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ContributionID pgtype.UUID `json:"contribution_id"`
+}
+
+func (q *Queries) GetActivePluginRemoteMCPSecretForUpdate(ctx context.Context, arg GetActivePluginRemoteMCPSecretForUpdateParams) (PluginRemoteMcpSecret, error) {
+ row := q.db.QueryRow(ctx, getActivePluginRemoteMCPSecretForUpdate,
+ arg.ID,
+ arg.WorkspaceID,
+ arg.InstallationID,
+ arg.ContributionID,
+ )
+ var i PluginRemoteMcpSecret
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.InstallationID,
+ &i.ContributionID,
+ &i.Version,
+ &i.Ciphertext,
+ &i.Hint,
+ &i.Status,
+ &i.CreatedBy,
+ &i.CreatedAt,
+ &i.RevokedAt,
+ )
+ return i, err
+}
+
+const getInstallationRemoteMCPContribution = `-- name: GetInstallationRemoteMCPContribution :one
+SELECT contribution.id, contribution.release_id, contribution.contribution_key, contribution.type, contribution.schema_version, contribution.display_name, contribution.description, contribution.entry_path, contribution.entry_digest, contribution.artifact_digest, contribution.required_daemon_features, contribution.ordinal, contribution.created_at, release.manifest
+FROM plugin_installation installation
+JOIN plugin_release release
+ ON release.id = installation.desired_release_id
+ AND release.plugin_id = installation.plugin_id
+ AND release.revocation_status = 'active'
+JOIN plugin_contribution contribution
+ ON contribution.release_id = release.id
+ AND contribution.type = 'tool.remote-mcp.v1'
+WHERE installation.id = $1
+ AND installation.workspace_id = $2
+ AND installation.uninstalled_at IS NULL
+ AND contribution.contribution_key = $3
+`
+
+type GetInstallationRemoteMCPContributionParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ContributionKey string `json:"contribution_key"`
+}
+
+type GetInstallationRemoteMCPContributionRow struct {
+ ID pgtype.UUID `json:"id"`
+ ReleaseID pgtype.UUID `json:"release_id"`
+ ContributionKey string `json:"contribution_key"`
+ Type string `json:"type"`
+ SchemaVersion int32 `json:"schema_version"`
+ DisplayName string `json:"display_name"`
+ Description string `json:"description"`
+ EntryPath string `json:"entry_path"`
+ EntryDigest string `json:"entry_digest"`
+ ArtifactDigest string `json:"artifact_digest"`
+ RequiredDaemonFeatures []byte `json:"required_daemon_features"`
+ Ordinal int32 `json:"ordinal"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ Manifest []byte `json:"manifest"`
+}
+
+func (q *Queries) GetInstallationRemoteMCPContribution(ctx context.Context, arg GetInstallationRemoteMCPContributionParams) (GetInstallationRemoteMCPContributionRow, error) {
+ row := q.db.QueryRow(ctx, getInstallationRemoteMCPContribution, arg.InstallationID, arg.WorkspaceID, arg.ContributionKey)
+ var i GetInstallationRemoteMCPContributionRow
+ err := row.Scan(
+ &i.ID,
+ &i.ReleaseID,
+ &i.ContributionKey,
+ &i.Type,
+ &i.SchemaVersion,
+ &i.DisplayName,
+ &i.Description,
+ &i.EntryPath,
+ &i.EntryDigest,
+ &i.ArtifactDigest,
+ &i.RequiredDaemonFeatures,
+ &i.Ordinal,
+ &i.CreatedAt,
+ &i.Manifest,
+ )
+ return i, err
+}
+
+const getInstallationRemoteMCPContributionByID = `-- name: GetInstallationRemoteMCPContributionByID :one
+SELECT contribution.id, contribution.release_id, contribution.contribution_key, contribution.type, contribution.schema_version, contribution.display_name, contribution.description, contribution.entry_path, contribution.entry_digest, contribution.artifact_digest, contribution.required_daemon_features, contribution.ordinal, contribution.created_at, release.manifest
+FROM plugin_installation installation
+JOIN plugin_release release
+ ON release.id = installation.desired_release_id
+ AND release.plugin_id = installation.plugin_id
+ AND release.revocation_status = 'active'
+JOIN plugin_contribution contribution
+ ON contribution.release_id = release.id
+ AND contribution.type = 'tool.remote-mcp.v1'
+WHERE installation.id = $1
+ AND installation.workspace_id = $2
+ AND installation.uninstalled_at IS NULL
+ AND contribution.id = $3
+`
+
+type GetInstallationRemoteMCPContributionByIDParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ContributionID pgtype.UUID `json:"contribution_id"`
+}
+
+type GetInstallationRemoteMCPContributionByIDRow struct {
+ ID pgtype.UUID `json:"id"`
+ ReleaseID pgtype.UUID `json:"release_id"`
+ ContributionKey string `json:"contribution_key"`
+ Type string `json:"type"`
+ SchemaVersion int32 `json:"schema_version"`
+ DisplayName string `json:"display_name"`
+ Description string `json:"description"`
+ EntryPath string `json:"entry_path"`
+ EntryDigest string `json:"entry_digest"`
+ ArtifactDigest string `json:"artifact_digest"`
+ RequiredDaemonFeatures []byte `json:"required_daemon_features"`
+ Ordinal int32 `json:"ordinal"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ Manifest []byte `json:"manifest"`
+}
+
+func (q *Queries) GetInstallationRemoteMCPContributionByID(ctx context.Context, arg GetInstallationRemoteMCPContributionByIDParams) (GetInstallationRemoteMCPContributionByIDRow, error) {
+ row := q.db.QueryRow(ctx, getInstallationRemoteMCPContributionByID, arg.InstallationID, arg.WorkspaceID, arg.ContributionID)
+ var i GetInstallationRemoteMCPContributionByIDRow
+ err := row.Scan(
+ &i.ID,
+ &i.ReleaseID,
+ &i.ContributionKey,
+ &i.Type,
+ &i.SchemaVersion,
+ &i.DisplayName,
+ &i.Description,
+ &i.EntryPath,
+ &i.EntryDigest,
+ &i.ArtifactDigest,
+ &i.RequiredDaemonFeatures,
+ &i.Ordinal,
+ &i.CreatedAt,
+ &i.Manifest,
+ )
+ return i, err
+}
+
+const getLatestPluginInstallationConfig = `-- name: GetLatestPluginInstallationConfig :one
+SELECT id, workspace_id, installation_id, contribution_id, revision, endpoint, public_config, auth_type, auth_header, secret_ref, approved_tools, schema_digest, failure_policy, reviewed_by, reviewed_at, created_by, created_at, discovered_tools, discovered_schema_digest FROM plugin_installation_config
+WHERE workspace_id = $1
+ AND installation_id = $2
+ AND contribution_id = $3
+ORDER BY revision DESC
+LIMIT 1
+`
+
+type GetLatestPluginInstallationConfigParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ContributionID pgtype.UUID `json:"contribution_id"`
+}
+
+func (q *Queries) GetLatestPluginInstallationConfig(ctx context.Context, arg GetLatestPluginInstallationConfigParams) (PluginInstallationConfig, error) {
+ row := q.db.QueryRow(ctx, getLatestPluginInstallationConfig, arg.WorkspaceID, arg.InstallationID, arg.ContributionID)
+ var i PluginInstallationConfig
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.InstallationID,
+ &i.ContributionID,
+ &i.Revision,
+ &i.Endpoint,
+ &i.PublicConfig,
+ &i.AuthType,
+ &i.AuthHeader,
+ &i.SecretRef,
+ &i.ApprovedTools,
+ &i.SchemaDigest,
+ &i.FailurePolicy,
+ &i.ReviewedBy,
+ &i.ReviewedAt,
+ &i.CreatedBy,
+ &i.CreatedAt,
+ &i.DiscoveredTools,
+ &i.DiscoveredSchemaDigest,
+ )
+ return i, err
+}
+
const getLatestPluginRelease = `-- name: GetLatestPluginRelease :one
SELECT release.id, release.plugin_id, release.version, release.manifest, release.manifest_digest, release.source_kind, release.source_ref, release.archive_digest, release.artifact_ref, release.artifact_digest, release.artifact_size, release.signature, release.signature_key_id, release.revocation_status, release.revoked_at, release.revocation_reason, release.published_at
FROM plugin_release release
@@ -1235,6 +1788,127 @@ func (q *Queries) ListLatestPluginGrants(ctx context.Context, installationID pgt
return items, nil
}
+const listLatestPluginInstallationConfigs = `-- name: ListLatestPluginInstallationConfigs :many
+SELECT DISTINCT ON (config.contribution_id) config.id, config.workspace_id, config.installation_id, config.contribution_id, config.revision, config.endpoint, config.public_config, config.auth_type, config.auth_header, config.secret_ref, config.approved_tools, config.schema_digest, config.failure_policy, config.reviewed_by, config.reviewed_at, config.created_by, config.created_at, config.discovered_tools, config.discovered_schema_digest
+FROM plugin_installation_config config
+WHERE config.workspace_id = $1
+ AND config.installation_id = $2
+ORDER BY config.contribution_id, config.revision DESC
+`
+
+type ListLatestPluginInstallationConfigsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+}
+
+func (q *Queries) ListLatestPluginInstallationConfigs(ctx context.Context, arg ListLatestPluginInstallationConfigsParams) ([]PluginInstallationConfig, error) {
+ rows, err := q.db.Query(ctx, listLatestPluginInstallationConfigs, arg.WorkspaceID, arg.InstallationID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []PluginInstallationConfig{}
+ for rows.Next() {
+ var i PluginInstallationConfig
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.InstallationID,
+ &i.ContributionID,
+ &i.Revision,
+ &i.Endpoint,
+ &i.PublicConfig,
+ &i.AuthType,
+ &i.AuthHeader,
+ &i.SecretRef,
+ &i.ApprovedTools,
+ &i.SchemaDigest,
+ &i.FailurePolicy,
+ &i.ReviewedBy,
+ &i.ReviewedAt,
+ &i.CreatedBy,
+ &i.CreatedAt,
+ &i.DiscoveredTools,
+ &i.DiscoveredSchemaDigest,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listPluginArtifactFilesByIDs = `-- name: ListPluginArtifactFilesByIDs :many
+SELECT id, release_id, path, digest, size_bytes, content, created_at FROM plugin_artifact_file
+WHERE id = ANY($1::uuid[])
+ORDER BY path, id
+`
+
+func (q *Queries) ListPluginArtifactFilesByIDs(ctx context.Context, ids []pgtype.UUID) ([]PluginArtifactFile, error) {
+ rows, err := q.db.Query(ctx, listPluginArtifactFilesByIDs, ids)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []PluginArtifactFile{}
+ for rows.Next() {
+ var i PluginArtifactFile
+ if err := rows.Scan(
+ &i.ID,
+ &i.ReleaseID,
+ &i.Path,
+ &i.Digest,
+ &i.SizeBytes,
+ &i.Content,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listPluginArtifactFilesByRelease = `-- name: ListPluginArtifactFilesByRelease :many
+SELECT id, release_id, path, digest, size_bytes, content, created_at FROM plugin_artifact_file
+WHERE release_id = $1
+ORDER BY path, id
+`
+
+func (q *Queries) ListPluginArtifactFilesByRelease(ctx context.Context, releaseID pgtype.UUID) ([]PluginArtifactFile, error) {
+ rows, err := q.db.Query(ctx, listPluginArtifactFilesByRelease, releaseID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []PluginArtifactFile{}
+ for rows.Next() {
+ var i PluginArtifactFile
+ if err := rows.Scan(
+ &i.ID,
+ &i.ReleaseID,
+ &i.Path,
+ &i.Digest,
+ &i.SizeBytes,
+ &i.Content,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listPluginCompilationContributions = `-- name: ListPluginCompilationContributions :many
WITH latest_grants AS (
SELECT DISTINCT ON (installation_id, capability)
@@ -1247,6 +1921,12 @@ latest_bindings AS (
installation_id, scope_type, scope_id, enabled, binding_revision
FROM plugin_binding
ORDER BY installation_id, scope_type, scope_id, binding_revision DESC
+),
+latest_configs AS (
+ SELECT DISTINCT ON (installation_id, contribution_id) id, workspace_id, installation_id, contribution_id, revision, endpoint, public_config, auth_type, auth_header, secret_ref, approved_tools, schema_digest, failure_policy, reviewed_by, reviewed_at, created_by, created_at, discovered_tools, discovered_schema_digest
+ FROM plugin_installation_config
+ WHERE workspace_id = $1
+ ORDER BY installation_id, contribution_id, revision DESC
)
SELECT
installation.id AS installation_id,
@@ -1275,7 +1955,18 @@ SELECT
binding.scope_id,
binding.enabled AS binding_enabled,
binding.binding_revision,
- grant_row.grant_revision
+ grant_row.grant_revision,
+ config.id AS config_id,
+ config.revision AS config_revision,
+ config.endpoint,
+ config.public_config,
+ config.auth_type,
+ config.auth_header,
+ config.secret_ref,
+ config.approved_tools,
+ config.schema_digest,
+ config.failure_policy,
+ config.reviewed_at
FROM plugin_installation installation
JOIN plugin_identity identity
ON identity.id = installation.plugin_id
@@ -1290,46 +1981,71 @@ JOIN plugin_artifact_file artifact
AND artifact.path = contribution.entry_path
JOIN latest_grants grant_row
ON grant_row.installation_id = installation.id
- AND grant_row.capability = 'agent.skill.contribute'
+ AND grant_row.capability = CASE contribution.type
+ WHEN 'agent.skill.v1' THEN 'agent.skill.contribute'
+ WHEN 'tool.remote-mcp.v1' THEN 'tool.remote-mcp.connect'
+ END
AND grant_row.decision = 'granted'
+LEFT JOIN latest_configs config
+ ON config.installation_id = installation.id
+ AND config.contribution_id = contribution.id
LEFT JOIN latest_bindings binding
ON binding.installation_id = installation.id
WHERE installation.workspace_id = $1
AND installation.uninstalled_at IS NULL
AND installation.enabled = TRUE
+ AND (
+ contribution.type = 'agent.skill.v1'
+ OR (
+ contribution.type = 'tool.remote-mcp.v1'
+ AND config.reviewed_at IS NOT NULL
+ AND jsonb_array_length(config.approved_tools) > 0
+ )
+ )
ORDER BY identity.plugin_key, contribution.ordinal,
contribution.contribution_key,
binding.scope_type NULLS FIRST, binding.scope_id NULLS FIRST
`
type ListPluginCompilationContributionsRow struct {
- InstallationID pgtype.UUID `json:"installation_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- DesiredGeneration int64 `json:"desired_generation"`
- PluginID pgtype.UUID `json:"plugin_id"`
- PluginKey string `json:"plugin_key"`
- ReleaseID pgtype.UUID `json:"release_id"`
- ReleaseVersion string `json:"release_version"`
- SourceKind string `json:"source_kind"`
- ArtifactRef string `json:"artifact_ref"`
- ArtifactDigest string `json:"artifact_digest"`
- ContributionID pgtype.UUID `json:"contribution_id"`
- ContributionKey string `json:"contribution_key"`
- ContributionType string `json:"contribution_type"`
- DisplayName string `json:"display_name"`
- Description string `json:"description"`
- EntryPath string `json:"entry_path"`
- EntryDigest string `json:"entry_digest"`
- RequiredDaemonFeatures []byte `json:"required_daemon_features"`
- Ordinal int32 `json:"ordinal"`
- ArtifactFileID pgtype.UUID `json:"artifact_file_id"`
- EntryContent string `json:"entry_content"`
- EntrySizeBytes int64 `json:"entry_size_bytes"`
- ScopeType pgtype.Text `json:"scope_type"`
- ScopeID pgtype.UUID `json:"scope_id"`
- BindingEnabled pgtype.Bool `json:"binding_enabled"`
- BindingRevision pgtype.Int8 `json:"binding_revision"`
- GrantRevision int64 `json:"grant_revision"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ DesiredGeneration int64 `json:"desired_generation"`
+ PluginID pgtype.UUID `json:"plugin_id"`
+ PluginKey string `json:"plugin_key"`
+ ReleaseID pgtype.UUID `json:"release_id"`
+ ReleaseVersion string `json:"release_version"`
+ SourceKind string `json:"source_kind"`
+ ArtifactRef string `json:"artifact_ref"`
+ ArtifactDigest string `json:"artifact_digest"`
+ ContributionID pgtype.UUID `json:"contribution_id"`
+ ContributionKey string `json:"contribution_key"`
+ ContributionType string `json:"contribution_type"`
+ DisplayName string `json:"display_name"`
+ Description string `json:"description"`
+ EntryPath string `json:"entry_path"`
+ EntryDigest string `json:"entry_digest"`
+ RequiredDaemonFeatures []byte `json:"required_daemon_features"`
+ Ordinal int32 `json:"ordinal"`
+ ArtifactFileID pgtype.UUID `json:"artifact_file_id"`
+ EntryContent string `json:"entry_content"`
+ EntrySizeBytes int64 `json:"entry_size_bytes"`
+ ScopeType pgtype.Text `json:"scope_type"`
+ ScopeID pgtype.UUID `json:"scope_id"`
+ BindingEnabled pgtype.Bool `json:"binding_enabled"`
+ BindingRevision pgtype.Int8 `json:"binding_revision"`
+ GrantRevision int64 `json:"grant_revision"`
+ ConfigID pgtype.UUID `json:"config_id"`
+ ConfigRevision pgtype.Int8 `json:"config_revision"`
+ Endpoint pgtype.Text `json:"endpoint"`
+ PublicConfig []byte `json:"public_config"`
+ AuthType pgtype.Text `json:"auth_type"`
+ AuthHeader pgtype.Text `json:"auth_header"`
+ SecretRef pgtype.UUID `json:"secret_ref"`
+ ApprovedTools []byte `json:"approved_tools"`
+ SchemaDigest pgtype.Text `json:"schema_digest"`
+ FailurePolicy pgtype.Text `json:"failure_policy"`
+ ReviewedAt pgtype.Timestamptz `json:"reviewed_at"`
}
func (q *Queries) ListPluginCompilationContributions(ctx context.Context, workspaceID pgtype.UUID) ([]ListPluginCompilationContributionsRow, error) {
@@ -1369,6 +2085,17 @@ func (q *Queries) ListPluginCompilationContributions(ctx context.Context, worksp
&i.BindingEnabled,
&i.BindingRevision,
&i.GrantRevision,
+ &i.ConfigID,
+ &i.ConfigRevision,
+ &i.Endpoint,
+ &i.PublicConfig,
+ &i.AuthType,
+ &i.AuthHeader,
+ &i.SecretRef,
+ &i.ApprovedTools,
+ &i.SchemaDigest,
+ &i.FailurePolicy,
+ &i.ReviewedAt,
); err != nil {
return nil, err
}
@@ -1697,6 +2424,36 @@ func (q *Queries) LockPluginRegistryKey(ctx context.Context, pluginKey string) e
return err
}
+const lockPluginRemoteMCPInstallation = `-- name: LockPluginRemoteMCPInstallation :one
+SELECT installation.id
+FROM plugin_installation installation
+JOIN plugin_release release
+ ON release.id = installation.desired_release_id
+ AND release.plugin_id = installation.plugin_id
+ AND release.revocation_status = 'active'
+JOIN plugin_contribution contribution
+ ON contribution.release_id = release.id
+ AND contribution.id = $1
+ AND contribution.type = 'tool.remote-mcp.v1'
+WHERE installation.id = $2
+ AND installation.workspace_id = $3
+ AND installation.uninstalled_at IS NULL
+FOR UPDATE OF installation
+`
+
+type LockPluginRemoteMCPInstallationParams struct {
+ ContributionID pgtype.UUID `json:"contribution_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) LockPluginRemoteMCPInstallation(ctx context.Context, arg LockPluginRemoteMCPInstallationParams) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, lockPluginRemoteMCPInstallation, arg.ContributionID, arg.InstallationID, arg.WorkspaceID)
+ var id pgtype.UUID
+ err := row.Scan(&id)
+ return id, err
+}
+
const retirePluginIdentity = `-- name: RetirePluginIdentity :one
UPDATE plugin_identity
SET retired_at = COALESCE(retired_at, now())
@@ -1761,6 +2518,54 @@ func (q *Queries) RevokePluginRelease(ctx context.Context, arg RevokePluginRelea
return i, err
}
+const revokePluginRemoteMCPSecrets = `-- name: RevokePluginRemoteMCPSecrets :many
+UPDATE plugin_remote_mcp_secret
+SET status = 'revoked', revoked_at = now()
+WHERE workspace_id = $1
+ AND installation_id = $2
+ AND contribution_id = $3
+ AND status = 'active'
+RETURNING id, workspace_id, installation_id, contribution_id, version, ciphertext, hint, status, created_by, created_at, revoked_at
+`
+
+type RevokePluginRemoteMCPSecretsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ContributionID pgtype.UUID `json:"contribution_id"`
+}
+
+func (q *Queries) RevokePluginRemoteMCPSecrets(ctx context.Context, arg RevokePluginRemoteMCPSecretsParams) ([]PluginRemoteMcpSecret, error) {
+ rows, err := q.db.Query(ctx, revokePluginRemoteMCPSecrets, arg.WorkspaceID, arg.InstallationID, arg.ContributionID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []PluginRemoteMcpSecret{}
+ for rows.Next() {
+ var i PluginRemoteMcpSecret
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.InstallationID,
+ &i.ContributionID,
+ &i.Version,
+ &i.Ciphertext,
+ &i.Hint,
+ &i.Status,
+ &i.CreatedBy,
+ &i.CreatedAt,
+ &i.RevokedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const setPluginInstallationDesiredState = `-- name: SetPluginInstallationDesiredState :one
WITH workspace_guard AS MATERIALIZED (
SELECT workspace.id
@@ -1886,3 +2691,50 @@ func (q *Queries) UninstallPluginInstallation(ctx context.Context, arg Uninstall
)
return i, err
}
+
+const updateActivePluginRemoteMCPSecret = `-- name: UpdateActivePluginRemoteMCPSecret :one
+UPDATE plugin_remote_mcp_secret
+SET ciphertext = $1,
+ hint = $2
+WHERE id = $3
+ AND workspace_id = $4
+ AND installation_id = $5
+ AND contribution_id = $6
+ AND status = 'active'
+RETURNING id, workspace_id, installation_id, contribution_id, version, ciphertext, hint, status, created_by, created_at, revoked_at
+`
+
+type UpdateActivePluginRemoteMCPSecretParams struct {
+ Ciphertext []byte `json:"ciphertext"`
+ Hint string `json:"hint"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ContributionID pgtype.UUID `json:"contribution_id"`
+}
+
+func (q *Queries) UpdateActivePluginRemoteMCPSecret(ctx context.Context, arg UpdateActivePluginRemoteMCPSecretParams) (PluginRemoteMcpSecret, error) {
+ row := q.db.QueryRow(ctx, updateActivePluginRemoteMCPSecret,
+ arg.Ciphertext,
+ arg.Hint,
+ arg.ID,
+ arg.WorkspaceID,
+ arg.InstallationID,
+ arg.ContributionID,
+ )
+ var i PluginRemoteMcpSecret
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.InstallationID,
+ &i.ContributionID,
+ &i.Version,
+ &i.Ciphertext,
+ &i.Hint,
+ &i.Status,
+ &i.CreatedBy,
+ &i.CreatedAt,
+ &i.RevokedAt,
+ )
+ return i, err
+}
diff --git a/server/pkg/db/generated/plugin_sql_test.go b/server/pkg/db/generated/plugin_sql_test.go
index 2f6f39d35e..ab24427802 100644
--- a/server/pkg/db/generated/plugin_sql_test.go
+++ b/server/pkg/db/generated/plugin_sql_test.go
@@ -160,6 +160,24 @@ func TestPluginLifecycleQueries(t *testing.T) {
t.Fatalf("binding revisions = %d, %d", firstBinding.BindingRevision, secondBinding.BindingRevision)
}
+ oauthStateHash := make([]byte, 32)
+ copy(oauthStateHash, []byte(suffix))
+ if _, err := tx.Exec(ctx, `
+ INSERT INTO plugin_remote_mcp_oauth_state (
+ state_hash, workspace_id, installation_id, contribution_id, actor_id,
+ endpoint, authorization_endpoint, token_endpoint, client_id,
+ redirect_uri, secret_ciphertext, expires_at
+ )
+ VALUES (
+ $1, $2, $3, $4, $2,
+ 'https://mcp.example/mcp', 'https://mcp.example/authorize',
+ 'https://mcp.example/token', 'plugin-query-test',
+ 'https://multica.example/oauth/callback', $5, now() + interval '10 minutes'
+ )
+ `, oauthStateHash, workspaceID, installation.ID, contribution.ID, []byte("encrypted-state")); err != nil {
+ t.Fatalf("create Remote MCP OAuth state: %v", err)
+ }
+
updated, err := queries.SetPluginInstallationDesiredState(ctx, db.SetPluginInstallationDesiredStateParams{
WorkspaceID: workspaceID,
DesiredReleaseID: release.ID,
@@ -199,6 +217,15 @@ func TestPluginLifecycleQueries(t *testing.T) {
if _, err := queries.GetPluginInstallation(ctx, installation.ID); !errors.Is(err, pgx.ErrNoRows) {
t.Fatalf("installation after workspace cleanup error = %v", err)
}
+ var oauthStateCount int
+ if err := tx.QueryRow(ctx, `
+ SELECT count(*) FROM plugin_remote_mcp_oauth_state WHERE workspace_id = $1
+ `, workspaceID).Scan(&oauthStateCount); err != nil {
+ t.Fatalf("count Remote MCP OAuth states after workspace cleanup: %v", err)
+ }
+ if oauthStateCount != 0 {
+ t.Fatalf("Remote MCP OAuth states after workspace cleanup = %d, want 0", oauthStateCount)
+ }
remainingContributions, err := queries.ListPluginContributionsByRelease(ctx, release.ID)
if err != nil {
t.Fatalf("ListPluginContributionsByRelease: %v", err)
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 8b83b9de56..fd9ea38721 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -487,6 +487,18 @@ deleted_workspace_state AS (
DELETE FROM plugin_workspace_capability_state
WHERE workspace_id = $1
),
+deleted_remote_mcp_oauth_states AS (
+ DELETE FROM plugin_remote_mcp_oauth_state
+ WHERE workspace_id = $1
+),
+deleted_remote_mcp_configs AS (
+ DELETE FROM plugin_installation_config
+ WHERE workspace_id = $1
+),
+deleted_remote_mcp_secrets AS (
+ DELETE FROM plugin_remote_mcp_secret
+ WHERE workspace_id = $1
+),
deleted_bindings AS (
DELETE FROM plugin_binding
WHERE installation_id IN (SELECT id FROM installations)
diff --git a/server/pkg/db/queries/plugin.sql b/server/pkg/db/queries/plugin.sql
index de1995bf7c..55ae57b914 100644
--- a/server/pkg/db/queries/plugin.sql
+++ b/server/pkg/db/queries/plugin.sql
@@ -94,6 +94,215 @@ SELECT * FROM plugin_contribution
WHERE release_id = $1
ORDER BY ordinal, id;
+-- name: GetInstallationRemoteMCPContribution :one
+SELECT contribution.*, release.manifest
+FROM plugin_installation installation
+JOIN plugin_release release
+ ON release.id = installation.desired_release_id
+ AND release.plugin_id = installation.plugin_id
+ AND release.revocation_status = 'active'
+JOIN plugin_contribution contribution
+ ON contribution.release_id = release.id
+ AND contribution.type = 'tool.remote-mcp.v1'
+WHERE installation.id = @installation_id
+ AND installation.workspace_id = @workspace_id
+ AND installation.uninstalled_at IS NULL
+ AND contribution.contribution_key = @contribution_key;
+
+-- name: GetInstallationRemoteMCPContributionByID :one
+SELECT contribution.*, release.manifest
+FROM plugin_installation installation
+JOIN plugin_release release
+ ON release.id = installation.desired_release_id
+ AND release.plugin_id = installation.plugin_id
+ AND release.revocation_status = 'active'
+JOIN plugin_contribution contribution
+ ON contribution.release_id = release.id
+ AND contribution.type = 'tool.remote-mcp.v1'
+WHERE installation.id = @installation_id
+ AND installation.workspace_id = @workspace_id
+ AND installation.uninstalled_at IS NULL
+ AND contribution.id = @contribution_id;
+
+-- name: LockPluginRemoteMCPInstallation :one
+SELECT installation.id
+FROM plugin_installation installation
+JOIN plugin_release release
+ ON release.id = installation.desired_release_id
+ AND release.plugin_id = installation.plugin_id
+ AND release.revocation_status = 'active'
+JOIN plugin_contribution contribution
+ ON contribution.release_id = release.id
+ AND contribution.id = @contribution_id
+ AND contribution.type = 'tool.remote-mcp.v1'
+WHERE installation.id = @installation_id
+ AND installation.workspace_id = @workspace_id
+ AND installation.uninstalled_at IS NULL
+FOR UPDATE OF installation;
+
+-- name: CreatePluginRemoteMCPSecret :one
+WITH parent AS MATERIALIZED (
+ SELECT installation.id, contribution.id AS contribution_id
+ FROM plugin_installation installation
+ JOIN plugin_release release
+ ON release.id = installation.desired_release_id
+ AND release.plugin_id = installation.plugin_id
+ AND release.revocation_status = 'active'
+ JOIN plugin_contribution contribution
+ ON contribution.release_id = release.id
+ AND contribution.id = @contribution_id
+ AND contribution.type = 'tool.remote-mcp.v1'
+ WHERE installation.id = @installation_id
+ AND installation.workspace_id = @workspace_id
+ AND installation.uninstalled_at IS NULL
+ FOR UPDATE OF installation
+ FOR KEY SHARE OF release, contribution
+), next_version AS (
+ SELECT COALESCE(MAX(version), 0) + 1 AS version
+ FROM plugin_remote_mcp_secret
+ WHERE installation_id = @installation_id
+ AND contribution_id = @contribution_id
+)
+INSERT INTO plugin_remote_mcp_secret (
+ workspace_id, installation_id, contribution_id, version,
+ ciphertext, hint, created_by
+)
+SELECT
+ @workspace_id, parent.id, parent.contribution_id, next_version.version,
+ @ciphertext, @hint, sqlc.narg('created_by')
+FROM parent, next_version
+RETURNING *;
+
+-- name: GetActivePluginRemoteMCPSecret :one
+SELECT * FROM plugin_remote_mcp_secret
+WHERE id = @id
+ AND workspace_id = @workspace_id
+ AND installation_id = @installation_id
+ AND contribution_id = @contribution_id
+ AND status = 'active';
+
+-- name: GetActivePluginRemoteMCPSecretForUpdate :one
+SELECT * FROM plugin_remote_mcp_secret
+WHERE id = @id
+ AND workspace_id = @workspace_id
+ AND installation_id = @installation_id
+ AND contribution_id = @contribution_id
+ AND status = 'active'
+FOR UPDATE;
+
+-- name: RevokePluginRemoteMCPSecrets :many
+UPDATE plugin_remote_mcp_secret
+SET status = 'revoked', revoked_at = now()
+WHERE workspace_id = @workspace_id
+ AND installation_id = @installation_id
+ AND contribution_id = @contribution_id
+ AND status = 'active'
+RETURNING *;
+
+-- name: UpdateActivePluginRemoteMCPSecret :one
+UPDATE plugin_remote_mcp_secret
+SET ciphertext = @ciphertext,
+ hint = @hint
+WHERE id = @id
+ AND workspace_id = @workspace_id
+ AND installation_id = @installation_id
+ AND contribution_id = @contribution_id
+ AND status = 'active'
+RETURNING *;
+
+-- name: CreatePluginRemoteMCPOAuthState :one
+INSERT INTO plugin_remote_mcp_oauth_state (
+ state_hash, workspace_id, installation_id, contribution_id, actor_id,
+ endpoint, public_config, failure_policy,
+ authorization_endpoint, token_endpoint, client_id, scope,
+ redirect_uri, return_to, secret_ciphertext, expires_at
+) VALUES (
+ @state_hash, @workspace_id, @installation_id, @contribution_id, @actor_id,
+ @endpoint, @public_config, @failure_policy,
+ @authorization_endpoint, @token_endpoint, @client_id, @scope,
+ @redirect_uri, @return_to, @secret_ciphertext, @expires_at
+)
+RETURNING *;
+
+-- name: ClaimPluginRemoteMCPOAuthState :one
+UPDATE plugin_remote_mcp_oauth_state
+SET consumed_at = now()
+WHERE state_hash = @state_hash
+ AND consumed_at IS NULL
+ AND expires_at > now()
+RETURNING *;
+
+-- name: DeleteExpiredPluginRemoteMCPOAuthStates :execrows
+DELETE FROM plugin_remote_mcp_oauth_state
+WHERE expires_at <= now() OR consumed_at < now() - interval '1 hour';
+
+-- name: CreatePluginInstallationConfig :one
+WITH parent AS MATERIALIZED (
+ SELECT installation.id, contribution.id AS contribution_id
+ FROM plugin_installation installation
+ JOIN plugin_release release
+ ON release.id = installation.desired_release_id
+ AND release.plugin_id = installation.plugin_id
+ AND release.revocation_status = 'active'
+ JOIN plugin_contribution contribution
+ ON contribution.release_id = release.id
+ AND contribution.id = @contribution_id
+ AND contribution.type = 'tool.remote-mcp.v1'
+ WHERE installation.id = @installation_id
+ AND installation.workspace_id = @workspace_id
+ AND installation.uninstalled_at IS NULL
+ AND (
+ (@auth_type::text = 'none' AND sqlc.narg('secret_ref')::uuid IS NULL)
+ OR EXISTS (
+ SELECT 1 FROM plugin_remote_mcp_secret secret
+ WHERE secret.id = sqlc.narg('secret_ref')::uuid
+ AND secret.workspace_id = @workspace_id
+ AND secret.installation_id = installation.id
+ AND secret.contribution_id = contribution.id
+ AND secret.status = 'active'
+ )
+ )
+ FOR UPDATE OF installation
+ FOR KEY SHARE OF release, contribution
+), next_revision AS (
+ SELECT COALESCE(MAX(revision), 0) + 1 AS revision
+ FROM plugin_installation_config
+ WHERE installation_id = @installation_id
+ AND contribution_id = @contribution_id
+)
+INSERT INTO plugin_installation_config (
+ workspace_id, installation_id, contribution_id, revision,
+ endpoint, public_config, auth_type, auth_header, secret_ref,
+ discovered_tools, discovered_schema_digest,
+ approved_tools, schema_digest, failure_policy,
+ reviewed_by, reviewed_at, created_by
+)
+SELECT
+ @workspace_id, parent.id, parent.contribution_id, next_revision.revision,
+ @endpoint, @public_config, @auth_type, @auth_header, sqlc.narg('secret_ref'),
+ @discovered_tools, sqlc.narg('discovered_schema_digest'),
+ @approved_tools, sqlc.narg('schema_digest'), @failure_policy,
+ sqlc.narg('reviewed_by'),
+ CASE WHEN sqlc.narg('reviewed_by')::uuid IS NULL THEN NULL ELSE now() END,
+ sqlc.narg('created_by')
+FROM parent, next_revision
+RETURNING *;
+
+-- name: GetLatestPluginInstallationConfig :one
+SELECT * FROM plugin_installation_config
+WHERE workspace_id = @workspace_id
+ AND installation_id = @installation_id
+ AND contribution_id = @contribution_id
+ORDER BY revision DESC
+LIMIT 1;
+
+-- name: ListLatestPluginInstallationConfigs :many
+SELECT DISTINCT ON (config.contribution_id) config.*
+FROM plugin_installation_config config
+WHERE config.workspace_id = @workspace_id
+ AND config.installation_id = @installation_id
+ORDER BY config.contribution_id, config.revision DESC;
+
-- name: ListPluginReleasesByPlugin :many
SELECT * FROM plugin_release
WHERE plugin_id = $1 AND revocation_status = 'active'
@@ -337,6 +546,16 @@ WHERE release_id = $1 AND path = $2;
SELECT * FROM plugin_artifact_file
WHERE id = $1;
+-- name: ListPluginArtifactFilesByRelease :many
+SELECT * FROM plugin_artifact_file
+WHERE release_id = $1
+ORDER BY path, id;
+
+-- name: ListPluginArtifactFilesByIDs :many
+SELECT * FROM plugin_artifact_file
+WHERE id = ANY(@ids::uuid[])
+ORDER BY path, id;
+
-- name: GetLatestPluginRelease :one
SELECT release.*
FROM plugin_release release
@@ -393,6 +612,12 @@ latest_bindings AS (
installation_id, scope_type, scope_id, enabled, binding_revision
FROM plugin_binding
ORDER BY installation_id, scope_type, scope_id, binding_revision DESC
+),
+latest_configs AS (
+ SELECT DISTINCT ON (installation_id, contribution_id) *
+ FROM plugin_installation_config
+ WHERE workspace_id = @workspace_id
+ ORDER BY installation_id, contribution_id, revision DESC
)
SELECT
installation.id AS installation_id,
@@ -421,7 +646,18 @@ SELECT
binding.scope_id,
binding.enabled AS binding_enabled,
binding.binding_revision,
- grant_row.grant_revision
+ grant_row.grant_revision,
+ config.id AS config_id,
+ config.revision AS config_revision,
+ config.endpoint,
+ config.public_config,
+ config.auth_type,
+ config.auth_header,
+ config.secret_ref,
+ config.approved_tools,
+ config.schema_digest,
+ config.failure_policy,
+ config.reviewed_at
FROM plugin_installation installation
JOIN plugin_identity identity
ON identity.id = installation.plugin_id
@@ -436,13 +672,27 @@ JOIN plugin_artifact_file artifact
AND artifact.path = contribution.entry_path
JOIN latest_grants grant_row
ON grant_row.installation_id = installation.id
- AND grant_row.capability = 'agent.skill.contribute'
+ AND grant_row.capability = CASE contribution.type
+ WHEN 'agent.skill.v1' THEN 'agent.skill.contribute'
+ WHEN 'tool.remote-mcp.v1' THEN 'tool.remote-mcp.connect'
+ END
AND grant_row.decision = 'granted'
+LEFT JOIN latest_configs config
+ ON config.installation_id = installation.id
+ AND config.contribution_id = contribution.id
LEFT JOIN latest_bindings binding
ON binding.installation_id = installation.id
WHERE installation.workspace_id = @workspace_id
AND installation.uninstalled_at IS NULL
AND installation.enabled = TRUE
+ AND (
+ contribution.type = 'agent.skill.v1'
+ OR (
+ contribution.type = 'tool.remote-mcp.v1'
+ AND config.reviewed_at IS NOT NULL
+ AND jsonb_array_length(config.approved_tools) > 0
+ )
+ )
ORDER BY identity.plugin_key, contribution.ordinal,
contribution.contribution_key,
binding.scope_type NULLS FIRST, binding.scope_id NULLS FIRST;
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index 5c2bd9c70e..6acec2c637 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -603,6 +603,18 @@ deleted_workspace_state AS (
DELETE FROM plugin_workspace_capability_state
WHERE workspace_id = $1
),
+deleted_remote_mcp_oauth_states AS (
+ DELETE FROM plugin_remote_mcp_oauth_state
+ WHERE workspace_id = $1
+),
+deleted_remote_mcp_configs AS (
+ DELETE FROM plugin_installation_config
+ WHERE workspace_id = $1
+),
+deleted_remote_mcp_secrets AS (
+ DELETE FROM plugin_remote_mcp_secret
+ WHERE workspace_id = $1
+),
deleted_bindings AS (
DELETE FROM plugin_binding
WHERE installation_id IN (SELECT id FROM installations)
diff --git a/server/pkg/plugincontract/artifact.go b/server/pkg/plugincontract/artifact.go
index 2863ce067f..37cb767a76 100644
--- a/server/pkg/plugincontract/artifact.go
+++ b/server/pkg/plugincontract/artifact.go
@@ -20,6 +20,8 @@ const (
MaxFileSize = 1 << 20
MaxSkillSize = 8 << 20
MaxSkillFiles = 256
+
+ ThirdPartyLicensesRoot = "THIRD_PARTY_LICENSES/"
)
type Artifact struct {
@@ -39,8 +41,9 @@ type ArtifactFile struct {
}
// ValidateArtifact verifies an uploaded ZIP without extracting it to disk. It
-// accepts only regular UTF-8 text files under declared contribution roots and
-// returns content-addressed metadata suitable for immutable release storage.
+// accepts only regular UTF-8 text files under declared contribution roots or
+// the non-executable third-party license root and returns content-addressed
+// metadata suitable for immutable release storage.
func ValidateArtifact(archive []byte) (Artifact, error) {
if len(archive) == 0 {
return Artifact{}, fmt.Errorf("plugin archive is empty")
@@ -135,10 +138,16 @@ func ValidateArtifact(archive []byte) (Artifact, error) {
if name == ManifestFilename {
continue
}
+ if isThirdPartyLicensePath(name) {
+ continue
+ }
root := contributionRoot(name, allowedRoots)
if root == "" {
return Artifact{}, fmt.Errorf("plugin archive path %q is outside a declared contribution", name)
}
+ if name != allowedRoots[root].Entry && skillCompanionCollidesWithEntry(name, root) {
+ return Artifact{}, fmt.Errorf("plugin archive path %q collides with reserved primary Skill content", name)
+ }
counts[root]++
sizes[root] += file.SizeBytes
if counts[root] > MaxSkillFiles {
@@ -165,6 +174,20 @@ func ValidateArtifact(archive []byte) (Artifact, error) {
}, nil
}
+func skillCompanionCollidesWithEntry(name, root string) bool {
+ relative := strings.TrimPrefix(name, root)
+ firstSegment := relative
+ if separator := strings.IndexByte(relative, '/'); separator >= 0 {
+ firstSegment = relative[:separator]
+ }
+ return strings.EqualFold(firstSegment, "SKILL.md")
+}
+
+func isThirdPartyLicensePath(name string) bool {
+ relative := strings.TrimPrefix(name, ThirdPartyLicensesRoot)
+ return relative != name && relative != ""
+}
+
func isInstallHookPath(name string) bool {
base := strings.ToLower(path.Base(name))
switch base {
diff --git a/server/pkg/plugincontract/artifact_test.go b/server/pkg/plugincontract/artifact_test.go
index 3e83b5b966..ae955a16ba 100644
--- a/server/pkg/plugincontract/artifact_test.go
+++ b/server/pkg/plugincontract/artifact_test.go
@@ -65,6 +65,33 @@ func TestValidateArtifactAcceptsReferencePlugin(t *testing.T) {
}
}
+func TestValidateArtifactAcceptsRemoteMCPOnlyPlugin(t *testing.T) {
+ archive := buildArchive(t, []zipFixtureFile{{
+ name: ManifestFilename, content: manifestJSON(t, validRemoteMCPManifest()),
+ }})
+ artifact, err := ValidateArtifact(archive)
+ if err != nil {
+ t.Fatalf("ValidateArtifact: %v", err)
+ }
+ if len(artifact.Files) != 1 || len(artifact.Manifest.Contributes.RemoteMCP) != 1 {
+ t.Fatalf("remote-only artifact files = %d, contributions = %d", len(artifact.Files), len(artifact.Manifest.Contributes.RemoteMCP))
+ }
+}
+
+func TestValidateArtifactAcceptsThirdPartyLicenseFiles(t *testing.T) {
+ files := append(referenceArchiveFiles(t), zipFixtureFile{
+ name: ThirdPartyLicensesRoot + "dependency-MIT.txt",
+ content: []byte("MIT License\n\nCopyright dependency author\n"),
+ })
+ artifact, err := ValidateArtifact(buildArchive(t, files))
+ if err != nil {
+ t.Fatalf("ValidateArtifact: %v", err)
+ }
+ if len(artifact.Files) != 4 {
+ t.Fatalf("files = %d, want 4", len(artifact.Files))
+ }
+}
+
func TestArtifactDigestIgnoresZipEntryOrder(t *testing.T) {
files := referenceArchiveFiles(t)
reversed := []zipFixtureFile{files[2], files[1], files[0]}
@@ -94,6 +121,7 @@ func TestValidateArtifactRejectsUnsafeOrUnownedFiles(t *testing.T) {
{name: "traversal", file: zipFixtureFile{name: "../escape.md", content: []byte("no")}, wantErr: "unsafe"},
{name: "backslash", file: zipFixtureFile{name: `skills\escape.md`, content: []byte("no")}, wantErr: "unsafe"},
{name: "unowned", file: zipFixtureFile{name: "README.md", content: []byte("no")}, wantErr: "outside a declared contribution"},
+ {name: "primary content descendant", file: zipFixtureFile{name: "skills/review-readiness/SKILL.md/hidden.txt", content: []byte("no")}, wantErr: "reserved primary Skill content"},
{name: "executable", file: zipFixtureFile{name: "skills/review-readiness/run.sh", content: []byte("echo no"), mode: 0o700}, wantErr: "executable"},
{name: "symlink", file: zipFixtureFile{name: "skills/review-readiness/link", content: []byte("target"), mode: fs.ModeSymlink | 0o777}, wantErr: "not a regular file"},
{name: "binary", file: zipFixtureFile{name: "skills/review-readiness/binary", content: []byte{0xff, 0xfe}}, wantErr: "not UTF-8 text"},
diff --git a/server/pkg/plugincontract/examples_test.go b/server/pkg/plugincontract/examples_test.go
new file mode 100644
index 0000000000..628dc5fc79
--- /dev/null
+++ b/server/pkg/plugincontract/examples_test.go
@@ -0,0 +1,33 @@
+package plugincontract
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestExamplePluginsSatisfyArtifactContract(t *testing.T) {
+ root := filepath.Join("..", "..", "..", "examples", "plugins")
+ entries, err := os.ReadDir(root)
+ if err != nil {
+ t.Fatalf("read example plugins: %v", err)
+ }
+
+ for _, entry := range entries {
+ if !entry.IsDir() {
+ continue
+ }
+ source := filepath.Join(root, entry.Name())
+ if _, err := os.Stat(filepath.Join(source, ManifestFilename)); err != nil {
+ if os.IsNotExist(err) {
+ continue
+ }
+ t.Fatalf("inspect %s manifest: %v", entry.Name(), err)
+ }
+ t.Run(entry.Name(), func(t *testing.T) {
+ if _, _, err := PackDirectory(source); err != nil {
+ t.Fatalf("pack example plugin: %v", err)
+ }
+ })
+ }
+}
diff --git a/server/pkg/plugincontract/manifest.go b/server/pkg/plugincontract/manifest.go
index 449f7baa4b..ca73b3beeb 100644
--- a/server/pkg/plugincontract/manifest.go
+++ b/server/pkg/plugincontract/manifest.go
@@ -8,6 +8,7 @@ import (
"encoding/json"
"fmt"
"io"
+ "net/url"
"regexp"
"strings"
)
@@ -18,9 +19,13 @@ const (
ContributionAgentSkillV1 = "agent.skill.v1"
CapabilityAgentSkillContribute = "agent.skill.contribute"
+ ContributionRemoteMCPV1 = "tool.remote-mcp.v1"
+ CapabilityRemoteMCPConnect = "tool.remote-mcp.connect"
+ RemoteMCPAnyToolIntent = "*"
DaemonFeatureExecutionManifestV1 = "execution-manifest-v1"
DaemonFeatureAgentSkillV1 = "agent-skill-v1"
+ DaemonFeatureRemoteMCPV1 = "remote-mcp-v1"
ManifestFilename = "multica.plugin.json"
MaxManifestSize = 1 << 20
@@ -42,6 +47,22 @@ type Manifest struct {
Contributes ManifestContributions `json:"contributes"`
}
+func remoteMCPHostAllowed(host string, policies []string) bool {
+ for _, policy := range policies {
+ policy = strings.ToLower(strings.TrimSuffix(policy, "."))
+ if host == policy {
+ return true
+ }
+ if strings.HasPrefix(policy, "*.") {
+ suffix := strings.TrimPrefix(policy, "*")
+ if strings.HasSuffix(host, suffix) && host != strings.TrimPrefix(suffix, ".") {
+ return true
+ }
+ }
+ }
+ return false
+}
+
type Metadata struct {
Key string `json:"key"`
Name string `json:"name"`
@@ -56,14 +77,59 @@ type Compatibility struct {
}
type ManifestContributions struct {
- AgentSkills []AgentSkillContribution `json:"agent_skills"`
+ AgentSkills []AgentSkillContribution `json:"agent_skills,omitempty"`
+ RemoteMCP []RemoteMCPContribution `json:"remote_mcp,omitempty"`
}
type AgentSkillContribution struct {
Key string `json:"key"`
Name string `json:"name"`
Description string `json:"description"`
- Entry string `json:"entry"`
+ // Entry is the canonical SKILL.md. Every other regular UTF-8 file below
+ // skills/<key>/ is carried as an immutable companion file in the same
+ // agent.skill.v1 bundle.
+ Entry string `json:"entry"`
+}
+
+// RemoteMCPContribution is a declarative request to connect an installation to
+// a remote MCP server. The package never contains an endpoint or credential:
+// those are workspace-owned, revisioned installation configuration. ToolIntent
+// is the maximum publisher-declared tool surface an administrator may approve.
+type RemoteMCPContribution struct {
+ Key string `json:"key"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ Transport string `json:"transport"`
+ ProtocolVersions []string `json:"protocol_versions"`
+ EndpointPolicy RemoteMCPEndpointPolicy `json:"endpoint_policy"`
+ Authentication RemoteMCPAuthentication `json:"authentication,omitempty"`
+ ToolIntent []RemoteMCPToolIntent `json:"tool_intent"`
+ ConfigurationSchema json.RawMessage `json:"configuration_schema,omitempty"`
+}
+
+type RemoteMCPEndpointPolicy struct {
+ // DefaultEndpoint is the publisher-suggested hosted endpoint used by the
+ // one-click Connect flow. It is configuration, never a grant: the host must
+ // also be covered by AllowedHosts and the server still applies its public
+ // HTTPS/SSRF checks before every discovery or execution request.
+ DefaultEndpoint string `json:"default_endpoint,omitempty"`
+ AllowedHosts []string `json:"allowed_hosts,omitempty"`
+}
+
+type RemoteMCPAuthentication struct {
+ Preferred string `json:"preferred,omitempty"`
+ Supported []string `json:"supported,omitempty"`
+}
+
+type RemoteMCPToolIntent struct {
+ // Name may be "*" for hosted MCP servers whose exact tool set is only
+ // available after authentication. The administrator must still explicitly
+ // approve discovered tool names, and execution pins each approved schema;
+ // newly discovered tools never become available automatically. Wildcard
+ // intent is conservatively classified as write until exact tools are known.
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ Risk string `json:"risk"`
}
// ParseManifest decodes a strict V1 manifest and returns the canonical bytes
@@ -139,25 +205,44 @@ func (m Manifest) Validate() error {
if err != nil {
return err
}
- if len(capabilities) != 1 || !capabilities[CapabilityAgentSkillContribute] {
- return fmt.Errorf("requested_capabilities must contain only %q in V1", CapabilityAgentSkillContribute)
+ wantedCapabilities := map[string]bool{}
+ if len(m.Contributes.AgentSkills) > 0 {
+ wantedCapabilities[CapabilityAgentSkillContribute] = true
+ }
+ if len(m.Contributes.RemoteMCP) > 0 {
+ wantedCapabilities[CapabilityRemoteMCPConnect] = true
+ }
+ if len(wantedCapabilities) == 0 {
+ return fmt.Errorf("contributes must contain at least one agent_skills or remote_mcp contribution")
+ }
+ if len(capabilities) != len(wantedCapabilities) {
+ return fmt.Errorf("requested_capabilities must exactly match declared capabilities %q", declaredCapabilityNames(wantedCapabilities))
+ }
+ for capability := range capabilities {
+ if !wantedCapabilities[capability] {
+ return fmt.Errorf("requested_capabilities contains unsupported capability %q", capability)
+ }
}
features, err := uniqueStrings("compatibility.required_daemon_features", m.Compatibility.RequiredDaemonFeatures)
if err != nil {
return err
}
- for _, required := range []string{DaemonFeatureExecutionManifestV1, DaemonFeatureAgentSkillV1} {
+ requiredFeatures := []string{DaemonFeatureExecutionManifestV1}
+ if len(m.Contributes.AgentSkills) > 0 {
+ requiredFeatures = append(requiredFeatures, DaemonFeatureAgentSkillV1)
+ }
+ if len(m.Contributes.RemoteMCP) > 0 {
+ requiredFeatures = append(requiredFeatures, DaemonFeatureRemoteMCPV1)
+ }
+ for _, required := range requiredFeatures {
if !features[required] {
return fmt.Errorf("compatibility.required_daemon_features must include %q", required)
}
}
- if len(m.Contributes.AgentSkills) == 0 {
- return fmt.Errorf("contributes.agent_skills must contain at least one contribution")
- }
- keys := make(map[string]bool, len(m.Contributes.AgentSkills))
- names := make(map[string]bool, len(m.Contributes.AgentSkills))
+ keys := make(map[string]bool, len(m.Contributes.AgentSkills)+len(m.Contributes.RemoteMCP))
+ names := make(map[string]bool, len(m.Contributes.AgentSkills)+len(m.Contributes.RemoteMCP))
for index, skill := range m.Contributes.AgentSkills {
field := fmt.Sprintf("contributes.agent_skills[%d]", index)
if !contributionKeyPattern.MatchString(skill.Key) {
@@ -186,10 +271,128 @@ func (m Manifest) Validate() error {
return fmt.Errorf("%s.entry must be %q", field, wantEntry)
}
}
+ for index, remote := range m.Contributes.RemoteMCP {
+ field := fmt.Sprintf("contributes.remote_mcp[%d]", index)
+ if err := validateContributionIdentity(field, remote.Key, remote.Name, remote.Description, keys, names); err != nil {
+ return err
+ }
+ if remote.Transport != "streamable-http" {
+ return fmt.Errorf("%s.transport must be %q", field, "streamable-http")
+ }
+ versions, err := uniqueStrings(field+".protocol_versions", remote.ProtocolVersions)
+ if err != nil {
+ return err
+ }
+ if len(versions) == 0 {
+ return fmt.Errorf("%s.protocol_versions must not be empty", field)
+ }
+ for version := range versions {
+ if version != "2025-03-26" && version != "2024-11-05" {
+ return fmt.Errorf("%s.protocol_versions contains unsupported version %q", field, version)
+ }
+ }
+ allowedHosts, err := uniqueStrings(field+".endpoint_policy.allowed_hosts", remote.EndpointPolicy.AllowedHosts)
+ if err != nil {
+ return err
+ }
+ for host := range allowedHosts {
+ if strings.ContainsAny(host, "/:@?#") || strings.HasPrefix(host, ".") || strings.HasSuffix(host, ".") || strings.ToLower(host) != host {
+ return fmt.Errorf("%s.endpoint_policy.allowed_hosts contains invalid host %q", field, host)
+ }
+ }
+ if remote.EndpointPolicy.DefaultEndpoint != "" {
+ endpoint, err := url.Parse(remote.EndpointPolicy.DefaultEndpoint)
+ if err != nil || endpoint.Scheme != "https" || endpoint.Hostname() == "" || endpoint.User != nil || endpoint.RawQuery != "" || endpoint.Fragment != "" {
+ return fmt.Errorf("%s.endpoint_policy.default_endpoint must be a plain HTTPS URL", field)
+ }
+ host := strings.ToLower(strings.TrimSuffix(endpoint.Hostname(), "."))
+ if !remoteMCPHostAllowed(host, remote.EndpointPolicy.AllowedHosts) {
+ return fmt.Errorf("%s.endpoint_policy.default_endpoint host must be covered by allowed_hosts", field)
+ }
+ }
+ authModes, err := uniqueStrings(field+".authentication.supported", remote.Authentication.Supported)
+ if err != nil {
+ return err
+ }
+ for mode := range authModes {
+ if mode != "none" && mode != "oauth" && mode != "bearer" && mode != "header" {
+ return fmt.Errorf("%s.authentication.supported contains unsupported mode %q", field, mode)
+ }
+ }
+ if remote.Authentication.Preferred != "" && !authModes[remote.Authentication.Preferred] {
+ return fmt.Errorf("%s.authentication.preferred must appear in supported", field)
+ }
+ if len(remote.ToolIntent) == 0 {
+ return fmt.Errorf("%s.tool_intent must not be empty", field)
+ }
+ toolNames := make(map[string]bool, len(remote.ToolIntent))
+ for toolIndex, tool := range remote.ToolIntent {
+ toolField := fmt.Sprintf("%s.tool_intent[%d]", field, toolIndex)
+ if tool.Name != RemoteMCPAnyToolIntent && !contributionKeyPattern.MatchString(tool.Name) && !regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_.:-]{0,127}$`).MatchString(tool.Name) {
+ return fmt.Errorf("%s.name is invalid", toolField)
+ }
+ if toolNames[tool.Name] {
+ return fmt.Errorf("%s contains duplicate tool name %q", field+".tool_intent", tool.Name)
+ }
+ toolNames[tool.Name] = true
+ if tool.Description != "" {
+ if err := validateDisplayText(toolField+".description", tool.Description, 2000); err != nil {
+ return err
+ }
+ }
+ if tool.Risk != "read" && tool.Risk != "write" {
+ return fmt.Errorf("%s.risk must be read or write", toolField)
+ }
+ if tool.Name == RemoteMCPAnyToolIntent && tool.Risk != "write" {
+ return fmt.Errorf("%s.risk must be write for wildcard tool intent", toolField)
+ }
+ }
+ if len(remote.ConfigurationSchema) > 0 {
+ var schema map[string]any
+ if err := json.Unmarshal(remote.ConfigurationSchema, &schema); err != nil {
+ return fmt.Errorf("%s.configuration_schema must be a JSON object: %w", field, err)
+ }
+ if schemaType, _ := schema["type"].(string); schemaType != "object" {
+ return fmt.Errorf("%s.configuration_schema.type must be object", field)
+ }
+ }
+ }
return nil
}
+func declaredCapabilityNames(capabilities map[string]bool) []string {
+ names := make([]string, 0, len(capabilities))
+ for _, capability := range []string{CapabilityAgentSkillContribute, CapabilityRemoteMCPConnect} {
+ if capabilities[capability] {
+ names = append(names, capability)
+ }
+ }
+ return names
+}
+
+func validateContributionIdentity(field, key, name, description string, keys, names map[string]bool) error {
+ if !contributionKeyPattern.MatchString(key) {
+ return fmt.Errorf("%s.key is invalid", field)
+ }
+ if strings.HasPrefix(key, "multica-") {
+ return fmt.Errorf("%s.key uses the reserved multica- namespace", field)
+ }
+ if keys[key] {
+ return fmt.Errorf("duplicate contribution key %q", key)
+ }
+ keys[key] = true
+ if err := validateDisplayText(field+".name", name, 160); err != nil {
+ return err
+ }
+ nameKey := strings.ToLower(name)
+ if names[nameKey] {
+ return fmt.Errorf("duplicate contribution name %q", name)
+ }
+ names[nameKey] = true
+ return validateDisplayText(field+".description", description, 2000)
+}
+
func validatePluginKey(key string) error {
if len(key) > 255 {
return fmt.Errorf("metadata.key exceeds 255 bytes")
diff --git a/server/pkg/plugincontract/manifest_test.go b/server/pkg/plugincontract/manifest_test.go
index dd2a335d84..1ad99bb855 100644
--- a/server/pkg/plugincontract/manifest_test.go
+++ b/server/pkg/plugincontract/manifest_test.go
@@ -102,3 +102,92 @@ func TestManifestRejectsDuplicateContributionIdentity(t *testing.T) {
t.Fatalf("Validate duplicate contribution error = %v", err)
}
}
+
+func validRemoteMCPManifest() Manifest {
+ manifest := validManifest()
+ manifest.Metadata.Key = "dev.local.fixture-mcp"
+ manifest.Metadata.Name = "Fixture MCP"
+ manifest.Contributes.AgentSkills = nil
+ manifest.Contributes.RemoteMCP = []RemoteMCPContribution{{
+ Key: "fixture-tools",
+ Name: "Fixture Tools",
+ Description: "Deterministic fixture tools.",
+ Transport: "streamable-http",
+ ProtocolVersions: []string{"2025-03-26", "2024-11-05"},
+ EndpointPolicy: RemoteMCPEndpointPolicy{
+ DefaultEndpoint: "https://mcp.example.test/mcp", AllowedHosts: []string{"mcp.example.test"},
+ },
+ Authentication: RemoteMCPAuthentication{Preferred: "oauth", Supported: []string{"oauth"}},
+ ToolIntent: []RemoteMCPToolIntent{
+ {Name: "fixture.read", Description: "Read fixture state.", Risk: "read"},
+ {Name: "fixture.write", Description: "Mutate fixture state.", Risk: "write"},
+ },
+ ConfigurationSchema: json.RawMessage(`{"type":"object","additionalProperties":false}`),
+ }}
+ manifest.RequestedCapabilities = []string{CapabilityRemoteMCPConnect}
+ manifest.Compatibility.RequiredDaemonFeatures = []string{
+ DaemonFeatureExecutionManifestV1,
+ DaemonFeatureRemoteMCPV1,
+ }
+ return manifest
+}
+
+func TestManifestAcceptsRemoteMCPOnlyAndMixedContributions(t *testing.T) {
+ remoteOnly := validRemoteMCPManifest()
+ if err := remoteOnly.Validate(); err != nil {
+ t.Fatalf("Validate remote-only manifest: %v", err)
+ }
+
+ mixed := remoteOnly
+ mixed.Contributes.AgentSkills = validManifest().Contributes.AgentSkills
+ mixed.RequestedCapabilities = []string{CapabilityAgentSkillContribute, CapabilityRemoteMCPConnect}
+ mixed.Compatibility.RequiredDaemonFeatures = append(mixed.Compatibility.RequiredDaemonFeatures, DaemonFeatureAgentSkillV1)
+ if err := mixed.Validate(); err != nil {
+ t.Fatalf("Validate mixed manifest: %v", err)
+ }
+}
+
+func TestManifestAcceptsReviewedWildcardRemoteMCPToolIntent(t *testing.T) {
+ manifest := validRemoteMCPManifest()
+ manifest.Contributes.RemoteMCP[0].ToolIntent = []RemoteMCPToolIntent{{
+ Name: RemoteMCPAnyToolIntent, Description: "Discover tools for explicit administrator review.", Risk: "write",
+ }}
+ if err := manifest.Validate(); err != nil {
+ t.Fatalf("Validate wildcard Remote MCP tool intent: %v", err)
+ }
+}
+
+func TestManifestRemoteMCPFailsClosed(t *testing.T) {
+ tests := []struct {
+ name string
+ edit func(*Manifest)
+ want string
+ }{
+ {name: "stdio transport", edit: func(m *Manifest) { m.Contributes.RemoteMCP[0].Transport = "stdio" }, want: "streamable-http"},
+ {name: "unsupported protocol", edit: func(m *Manifest) { m.Contributes.RemoteMCP[0].ProtocolVersions = []string{"2026-01-01"} }, want: "unsupported version"},
+ {name: "secret-looking endpoint", edit: func(m *Manifest) {
+ m.Contributes.RemoteMCP[0].EndpointPolicy.AllowedHosts = []string{"https://[email protected]"}
+ }, want: "invalid host"},
+ {name: "default endpoint outside allowlist", edit: func(m *Manifest) {
+ m.Contributes.RemoteMCP[0].EndpointPolicy.DefaultEndpoint = "https://other.example/mcp"
+ }, want: "covered by allowed_hosts"},
+ {name: "preferred auth not supported", edit: func(m *Manifest) {
+ m.Contributes.RemoteMCP[0].Authentication.Preferred = "bearer"
+ }, want: "must appear in supported"},
+ {name: "invalid risk", edit: func(m *Manifest) { m.Contributes.RemoteMCP[0].ToolIntent[0].Risk = "admin" }, want: "read or write"},
+ {name: "wildcard understates risk", edit: func(m *Manifest) {
+ m.Contributes.RemoteMCP[0].ToolIntent = []RemoteMCPToolIntent{{Name: RemoteMCPAnyToolIntent, Risk: "read"}}
+ }, want: "must be write for wildcard"},
+ {name: "missing capability", edit: func(m *Manifest) { m.RequestedCapabilities = nil }, want: "requested_capabilities"},
+ {name: "missing daemon feature", edit: func(m *Manifest) { m.Compatibility.RequiredDaemonFeatures = []string{DaemonFeatureExecutionManifestV1} }, want: DaemonFeatureRemoteMCPV1},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ manifest := validRemoteMCPManifest()
+ test.edit(&manifest)
+ if err := manifest.Validate(); err == nil || !strings.Contains(err.Error(), test.want) {
+ t.Fatalf("Validate error = %v, want containing %q", err, test.want)
+ }
+ })
+ }
+}
diff --git a/server/pkg/plugincontract/release.go b/server/pkg/plugincontract/release.go
index ed346813e9..d9ddaab3e9 100644
--- a/server/pkg/plugincontract/release.go
+++ b/server/pkg/plugincontract/release.go
@@ -88,7 +88,7 @@ func ValidateReleaseCandidate(candidate ReleaseCandidate, verifier ReleaseVerifi
for _, file := range artifact.Files {
files[file.Path] = file
}
- contributions := make([]ValidatedContribution, 0, len(artifact.Manifest.Contributes.AgentSkills))
+ contributions := make([]ValidatedContribution, 0, len(artifact.Manifest.Contributes.AgentSkills)+len(artifact.Manifest.Contributes.RemoteMCP))
for ordinal, skill := range artifact.Manifest.Contributes.AgentSkills {
entry := files[skill.Entry]
contributions = append(contributions, ValidatedContribution{
@@ -100,10 +100,25 @@ func ValidateReleaseCandidate(candidate ReleaseCandidate, verifier ReleaseVerifi
EntryPath: skill.Entry,
EntryDigest: entry.Digest,
ArtifactDigest: artifact.ArtifactDigest,
- RequiredDaemonFeatures: append([]string(nil), artifact.Manifest.Compatibility.RequiredDaemonFeatures...),
+ RequiredDaemonFeatures: []string{DaemonFeatureExecutionManifestV1, DaemonFeatureAgentSkillV1},
Ordinal: int32(ordinal),
})
}
+ manifestEntry := files[ManifestFilename]
+ for index, remote := range artifact.Manifest.Contributes.RemoteMCP {
+ contributions = append(contributions, ValidatedContribution{
+ Key: remote.Key,
+ Type: ContributionRemoteMCPV1,
+ SchemaVersion: 1,
+ DisplayName: remote.Name,
+ Description: remote.Description,
+ EntryPath: ManifestFilename,
+ EntryDigest: manifestEntry.Digest,
+ ArtifactDigest: artifact.ArtifactDigest,
+ RequiredDaemonFeatures: []string{DaemonFeatureExecutionManifestV1, DaemonFeatureRemoteMCPV1},
+ Ordinal: int32(len(artifact.Manifest.Contributes.AgentSkills) + index),
+ })
+ }
return ValidatedRelease{
Manifest: artifact.Manifest,
diff --git a/server/pkg/plugincontract/release_test.go b/server/pkg/plugincontract/release_test.go
index 823391048e..ade2e67e5b 100644
--- a/server/pkg/plugincontract/release_test.go
+++ b/server/pkg/plugincontract/release_test.go
@@ -88,3 +88,20 @@ func TestValidateReleaseCandidateAllowsUnsignedPrivateDev(t *testing.T) {
t.Fatalf("validated private-dev release = %#v", validated)
}
}
+
+func TestValidateReleaseCandidateCompilesRemoteMCPAdapter(t *testing.T) {
+ archive := buildArchive(t, []zipFixtureFile{{name: ManifestFilename, content: manifestJSON(t, validRemoteMCPManifest())}})
+ validated, err := ValidateReleaseCandidate(ReleaseCandidate{
+ Archive: archive, SourceKind: SourcePrivateDev, SourceRef: "private://fixture",
+ }, nil)
+ if err != nil {
+ t.Fatalf("ValidateReleaseCandidate: %v", err)
+ }
+ if len(validated.Contributions) != 1 {
+ t.Fatalf("contributions = %d, want 1", len(validated.Contributions))
+ }
+ got := validated.Contributions[0]
+ if got.Type != ContributionRemoteMCPV1 || got.EntryPath != ManifestFilename || got.EntryDigest != validated.ManifestDigest {
+ t.Fatalf("remote MCP contribution = %#v", got)
+ }
+}
diff --git a/server/pkg/pluginruntime/runtime.go b/server/pkg/pluginruntime/runtime.go
index 8f3a2a4081..b5ed4fda33 100644
--- a/server/pkg/pluginruntime/runtime.go
+++ b/server/pkg/pluginruntime/runtime.go
@@ -11,7 +11,7 @@ import (
)
const (
- CompilerVersion = "plugin-compiler-v1"
+ CompilerVersion = "plugin-compiler-v2"
ComposerVersion = "plugin-composer-v1"
SchemaVersion = 1
)
@@ -19,30 +19,82 @@ const (
// CompiledEntry is one contribution made available at a workspace or agent
// scope. Execution manifests copy these entries verbatim at enqueue time.
type CompiledEntry struct {
- PluginID string `json:"plugin_id"`
- PluginKey string `json:"plugin_key"`
- InstallationID string `json:"installation_id"`
- ReleaseID string `json:"release_id"`
- ReleaseVersion string `json:"release_version"`
- ContributionID string `json:"contribution_id"`
- ContributionKey string `json:"contribution_key"`
- ContributionType string `json:"contribution_type"`
- DisplayName string `json:"display_name"`
- Description string `json:"description,omitempty"`
- SourceKind string `json:"source_kind"`
- ArtifactFileID string `json:"artifact_file_id"`
- ArtifactRef string `json:"artifact_ref"`
- ArtifactDigest string `json:"artifact_digest"`
- EntryPath string `json:"entry_path"`
- EntryDigest string `json:"entry_digest"`
- RequiredDaemonFeatures []string `json:"required_daemon_features"`
- Ordinal int32 `json:"ordinal"`
- ScopeType string `json:"scope_type"`
- ScopeID string `json:"scope_id"`
- ExcludedAgentIDs []string `json:"excluded_agent_ids,omitempty"`
- SkillBundleHash string `json:"skill_bundle_hash"`
- SkillSizeBytes int64 `json:"skill_size_bytes"`
- SkillFileCount int `json:"skill_file_count"`
+ PluginID string `json:"plugin_id"`
+ PluginKey string `json:"plugin_key"`
+ InstallationID string `json:"installation_id"`
+ ReleaseID string `json:"release_id"`
+ ReleaseVersion string `json:"release_version"`
+ ContributionID string `json:"contribution_id"`
+ ContributionKey string `json:"contribution_key"`
+ ContributionType string `json:"contribution_type"`
+ DisplayName string `json:"display_name"`
+ Description string `json:"description,omitempty"`
+ SourceKind string `json:"source_kind"`
+ ArtifactFileID string `json:"artifact_file_id"`
+ ArtifactRef string `json:"artifact_ref"`
+ ArtifactDigest string `json:"artifact_digest"`
+ EntryPath string `json:"entry_path"`
+ EntryDigest string `json:"entry_digest"`
+ RequiredDaemonFeatures []string `json:"required_daemon_features"`
+ Ordinal int32 `json:"ordinal"`
+ ScopeType string `json:"scope_type"`
+ ScopeID string `json:"scope_id"`
+ ExcludedAgentIDs []string `json:"excluded_agent_ids,omitempty"`
+ SkillBundleHash string `json:"skill_bundle_hash,omitempty"`
+ SkillSizeBytes int64 `json:"skill_size_bytes,omitempty"`
+ SkillFileCount int `json:"skill_file_count,omitempty"`
+ SkillFiles []SkillFile `json:"skill_files,omitempty"`
+ ConfigID string `json:"config_id,omitempty"`
+ ConfigRevision int64 `json:"config_revision,omitempty"`
+ Endpoint string `json:"endpoint,omitempty"`
+ PublicConfig json.RawMessage `json:"public_config,omitempty"`
+ SecretRef string `json:"secret_ref,omitempty"`
+ AuthType string `json:"auth_type,omitempty"`
+ AuthHeader string `json:"auth_header,omitempty"`
+ ApprovedTools []RemoteMCPTool `json:"approved_tools,omitempty"`
+ ToolSchemaDigest string `json:"tool_schema_digest,omitempty"`
+ FailurePolicy string `json:"failure_policy,omitempty"`
+ Transport string `json:"transport,omitempty"`
+ ProtocolVersions []string `json:"protocol_versions,omitempty"`
+ EndpointAllowedHosts []string `json:"endpoint_allowed_hosts,omitempty"`
+}
+
+// SkillFile pins one companion file from an agent.skill.v1 contribution.
+// Path is relative to the contribution's skills/<key>/ root; SKILL.md remains
+// pinned separately by ArtifactFileID, EntryPath, and EntryDigest.
+type SkillFile struct {
+ ArtifactFileID string `json:"artifact_file_id"`
+ Path string `json:"path"`
+ Digest string `json:"digest"`
+ SizeBytes int64 `json:"size_bytes"`
+}
+
+type RemoteMCPTool struct {
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ InputSchema json.RawMessage `json:"input_schema"`
+ SchemaDigest string `json:"schema_digest"`
+ Risk string `json:"risk,omitempty"`
+}
+
+// RemoteMCPConnection is claim-time, task-scoped connection metadata resolved
+// from a pinned entry. Credentials are intentionally absent from this wire
+// type and are resolved just-in-time by the daemon broker.
+type RemoteMCPConnection struct {
+ InstallationID string `json:"installation_id"`
+ ContributionID string `json:"contribution_id"`
+ ContributionKey string `json:"contribution_key"`
+ ConfigID string `json:"config_id"`
+ ConfigRevision int64 `json:"config_revision"`
+ Endpoint string `json:"endpoint"`
+ PublicConfig json.RawMessage `json:"public_config,omitempty"`
+ Transport string `json:"transport"`
+ ProtocolVersions []string `json:"protocol_versions"`
+ EndpointAllowedHosts []string `json:"endpoint_allowed_hosts,omitempty"`
+ CredentialHeader string `json:"credential_header,omitempty"`
+ ApprovedTools []RemoteMCPTool `json:"approved_tools"`
+ ToolSchemaDigest string `json:"tool_schema_digest"`
+ FailurePolicy string `json:"failure_policy"`
}
type SnapshotPayload struct {
@@ -56,6 +108,17 @@ func Canonicalize(entries []CompiledEntry) {
for i := range entries {
sort.Strings(entries[i].ExcludedAgentIDs)
sort.Strings(entries[i].RequiredDaemonFeatures)
+ sort.Strings(entries[i].ProtocolVersions)
+ sort.Strings(entries[i].EndpointAllowedHosts)
+ sort.Slice(entries[i].SkillFiles, func(left, right int) bool {
+ if entries[i].SkillFiles[left].Path != entries[i].SkillFiles[right].Path {
+ return entries[i].SkillFiles[left].Path < entries[i].SkillFiles[right].Path
+ }
+ return entries[i].SkillFiles[left].ArtifactFileID < entries[i].SkillFiles[right].ArtifactFileID
+ })
+ sort.Slice(entries[i].ApprovedTools, func(left, right int) bool {
+ return entries[i].ApprovedTools[left].Name < entries[i].ApprovedTools[right].Name
+ })
}
sort.Slice(entries, func(i, j int) bool {
left, right := entries[i], entries[j]
diff --git a/server/pkg/pluginruntime/runtime_test.go b/server/pkg/pluginruntime/runtime_test.go
index 2ee5608607..09a6976ac5 100644
--- a/server/pkg/pluginruntime/runtime_test.go
+++ b/server/pkg/pluginruntime/runtime_test.go
@@ -20,3 +20,33 @@ func TestSnapshotDigestCanonicalizesEntryOrder(t *testing.T) {
t.Fatalf("snapshot digest is not canonical: %s != %s", first, second)
}
}
+
+func TestSnapshotDigestCanonicalizesSkillFileOrder(t *testing.T) {
+ left := []CompiledEntry{{
+ PluginKey: "example.plugin",
+ ContributionKey: "community-skill",
+ SkillFiles: []SkillFile{
+ {ArtifactFileID: "file-b", Path: "references/b.md", Digest: "sha256:b", SizeBytes: 2},
+ {ArtifactFileID: "file-a", Path: "agents/openai.yaml", Digest: "sha256:a", SizeBytes: 1},
+ },
+ }}
+ right := []CompiledEntry{{
+ PluginKey: "example.plugin",
+ ContributionKey: "community-skill",
+ SkillFiles: []SkillFile{
+ {ArtifactFileID: "file-a", Path: "agents/openai.yaml", Digest: "sha256:a", SizeBytes: 1},
+ {ArtifactFileID: "file-b", Path: "references/b.md", Digest: "sha256:b", SizeBytes: 2},
+ },
+ }}
+ first, err := SnapshotDigest(map[string]int64{"installation": 1}, left)
+ if err != nil {
+ t.Fatal(err)
+ }
+ second, err := SnapshotDigest(map[string]int64{"installation": 1}, right)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if first != second {
+ t.Fatalf("snapshot digest depends on Skill file order: %s != %s", first, second)
+ }
+}
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index f8ed42dc96..cffa36c951 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -7,6 +7,7 @@ const (
DaemonCapabilityCoalescedCommentsV1 = "coalesced-comments-v1"
DaemonCapabilityExecutionManifestV1 = "execution-manifest-v1"
DaemonCapabilityAgentSkillV1 = "agent-skill-v1"
+ DaemonCapabilityRemoteMCPV1 = "remote-mcp-v1"
// DaemonCapabilityLocalWorktreeV1 advertises that the daemon implements
// worktree mode for local_directory resources (execution_mode=worktree).
//
diff --git a/server/pkg/remotemcp/client.go b/server/pkg/remotemcp/client.go
new file mode 100644
index 0000000000..edcb96fd5a
--- /dev/null
+++ b/server/pkg/remotemcp/client.go
@@ -0,0 +1,374 @@
+// Package remotemcp implements the security boundary shared by Remote MCP
+// Plugin discovery and the daemon's task-scoped broker.
+package remotemcp
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/netip"
+ "net/url"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+ "github.com/multica-ai/multica/server/pkg/pluginruntime"
+)
+
+const (
+ MaxResponseBytes = 4 << 20
+ ConnectTimeout = 10 * time.Second
+ CallTimeout = 30 * time.Second
+)
+
+type Resolver interface {
+ LookupNetIP(context.Context, string, string) ([]netip.Addr, error)
+}
+
+func ValidatePublicHTTPSEndpoint(ctx context.Context, raw string, allowedHosts []string, resolver Resolver) (*url.URL, error) {
+ endpoint, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil {
+ return nil, fmt.Errorf("parse endpoint: %w", err)
+ }
+ 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")
+ }
+ host := strings.ToLower(strings.TrimSuffix(endpoint.Hostname(), "."))
+ if host == "localhost" || strings.HasSuffix(host, ".localhost") {
+ return nil, errors.New("endpoint host is not public")
+ }
+ if len(allowedHosts) > 0 && !hostAllowed(host, allowedHosts) {
+ return nil, errors.New("endpoint host is outside the Plugin endpoint policy")
+ }
+ if resolver == nil {
+ resolver = net.DefaultResolver
+ }
+ addresses, err := resolver.LookupNetIP(ctx, "ip", host)
+ if err != nil || len(addresses) == 0 {
+ return nil, fmt.Errorf("resolve endpoint host: %w", err)
+ }
+ for _, address := range addresses {
+ if !isPublicAddress(address.Unmap()) {
+ return nil, fmt.Errorf("endpoint host resolves to non-public address %s", address)
+ }
+ }
+ return endpoint, nil
+}
+
+func hostAllowed(host string, policies []string) bool {
+ for _, policy := range policies {
+ policy = strings.ToLower(strings.TrimSuffix(policy, "."))
+ if host == policy {
+ return true
+ }
+ if strings.HasPrefix(policy, "*.") {
+ suffix := strings.TrimPrefix(policy, "*")
+ if strings.HasSuffix(host, suffix) && host != strings.TrimPrefix(suffix, ".") {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func isPublicAddress(address netip.Addr) bool {
+ if !address.IsValid() || address.IsPrivate() || address.IsLoopback() || address.IsLinkLocalUnicast() || address.IsLinkLocalMulticast() || address.IsMulticast() || address.IsUnspecified() {
+ return false
+ }
+ // IANA special-purpose and metadata ranges not covered by netip's helpers.
+ blocked := []netip.Prefix{
+ netip.MustParsePrefix("100.64.0.0/10"),
+ netip.MustParsePrefix("192.0.0.0/24"),
+ netip.MustParsePrefix("192.0.2.0/24"),
+ netip.MustParsePrefix("198.18.0.0/15"),
+ netip.MustParsePrefix("198.51.100.0/24"),
+ netip.MustParsePrefix("203.0.113.0/24"),
+ netip.MustParsePrefix("224.0.0.0/4"),
+ netip.MustParsePrefix("240.0.0.0/4"),
+ netip.MustParsePrefix("2001:db8::/32"),
+ netip.MustParsePrefix("fc00::/7"),
+ netip.MustParsePrefix("fe80::/10"),
+ }
+ for _, prefix := range blocked {
+ if prefix.Contains(address) {
+ return false
+ }
+ }
+ return address.IsGlobalUnicast()
+}
+
+func NewSecureHTTPClient(endpoint *url.URL) *http.Client {
+ dialer := &net.Dialer{Timeout: ConnectTimeout, KeepAlive: 30 * time.Second}
+ transport := http.DefaultTransport.(*http.Transport).Clone()
+ transport.Proxy = nil
+ transport.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
+ host, port, err := net.SplitHostPort(address)
+ if err != nil {
+ return nil, err
+ }
+ if !strings.EqualFold(strings.TrimSuffix(host, "."), strings.TrimSuffix(endpoint.Hostname(), ".")) {
+ return nil, errors.New("remote MCP redirect changed endpoint host")
+ }
+ addresses, err := net.DefaultResolver.LookupNetIP(ctx, "ip", host)
+ if err != nil || len(addresses) == 0 {
+ return nil, fmt.Errorf("resolve endpoint host: %w", err)
+ }
+ for _, candidate := range addresses {
+ candidate = candidate.Unmap()
+ if !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))
+ if dialErr == nil {
+ return connection, nil
+ }
+ }
+ return nil, errors.New("connect to remote MCP endpoint failed")
+ }
+ return &http.Client{
+ Timeout: CallTimeout,
+ Transport: transport,
+ CheckRedirect: func(*http.Request, []*http.Request) error {
+ return errors.New("remote MCP redirects are not allowed")
+ },
+ }
+}
+
+type rpcResponse struct {
+ JSONRPC string `json:"jsonrpc"`
+ ID json.RawMessage `json:"id"`
+ Result json.RawMessage `json:"result"`
+ Error *struct {
+ Code int `json:"code"`
+ Message string `json:"message"`
+ } `json:"error,omitempty"`
+}
+
+type discoveredTool struct {
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ InputSchema json.RawMessage `json:"inputSchema"`
+}
+
+func Discover(ctx context.Context, rawEndpoint string, allowedHosts, protocolVersions []string, headers http.Header) ([]pluginruntime.RemoteMCPTool, string, error) {
+ endpoint, err := ValidatePublicHTTPSEndpoint(ctx, rawEndpoint, allowedHosts, nil)
+ if err != nil {
+ return nil, "", err
+ }
+ client := NewSecureHTTPClient(endpoint)
+ sessionID := ""
+ protocolVersion := "2025-03-26"
+ if len(protocolVersions) > 0 {
+ protocolVersion = protocolVersions[0]
+ }
+ initialize := map[string]any{
+ "jsonrpc": "2.0", "id": 1, "method": "initialize",
+ "params": map[string]any{
+ "protocolVersion": protocolVersion,
+ "capabilities": map[string]any{},
+ "clientInfo": map[string]any{"name": "multica-plugin-review", "version": "1"},
+ },
+ }
+ initializeResponse, responseHeaders, err := call(ctx, client, endpoint, headers, sessionID, initialize)
+ if err != nil {
+ return nil, "", fmt.Errorf("initialize remote MCP: %w", err)
+ }
+ sessionID = responseHeaders.Get("Mcp-Session-Id")
+ var initialized struct {
+ ProtocolVersion string `json:"protocolVersion"`
+ }
+ if err := json.Unmarshal(initializeResponse.Result, &initialized); err != nil || !containsString(protocolVersions, initialized.ProtocolVersion) {
+ return nil, "", fmt.Errorf("remote MCP negotiated unsupported protocol version %q", initialized.ProtocolVersion)
+ }
+ if err := notify(ctx, client, endpoint, headers, sessionID, map[string]any{
+ "jsonrpc": "2.0", "method": "notifications/initialized", "params": map[string]any{},
+ }); err != nil {
+ return nil, "", fmt.Errorf("confirm remote MCP initialization: %w", err)
+ }
+ toolsResponse, _, err := call(ctx, client, endpoint, headers, sessionID, map[string]any{
+ "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": map[string]any{},
+ })
+ if err != nil {
+ return nil, "", fmt.Errorf("list remote MCP tools: %w", err)
+ }
+ var result struct {
+ Tools []discoveredTool `json:"tools"`
+ }
+ if err := json.Unmarshal(toolsResponse.Result, &result); err != nil {
+ return nil, "", fmt.Errorf("decode tools/list result: %w", err)
+ }
+ tools := make([]pluginruntime.RemoteMCPTool, 0, len(result.Tools))
+ seen := map[string]bool{}
+ for _, tool := range result.Tools {
+ if strings.TrimSpace(tool.Name) == "" || seen[tool.Name] {
+ return nil, "", errors.New("remote MCP returned an invalid or duplicate tool name")
+ }
+ seen[tool.Name] = true
+ canonical, err := canonicalJSON(tool.InputSchema)
+ if err != nil {
+ return nil, "", fmt.Errorf("tool %q input schema: %w", tool.Name, err)
+ }
+ tools = append(tools, pluginruntime.RemoteMCPTool{
+ Name: tool.Name, Description: tool.Description, InputSchema: canonical,
+ SchemaDigest: plugincontract.DigestBytes(canonical),
+ })
+ }
+ sort.Slice(tools, func(i, j int) bool { return tools[i].Name < tools[j].Name })
+ digest, err := ToolSetDigest(tools)
+ if err != nil {
+ return nil, "", err
+ }
+ return tools, digest, nil
+}
+
+func containsString(values []string, wanted string) bool {
+ for _, value := range values {
+ if value == wanted {
+ return true
+ }
+ }
+ return false
+}
+
+func notify(ctx context.Context, client *http.Client, endpoint *url.URL, headers http.Header, sessionID string, payload any) error {
+ body, err := json.Marshal(payload)
+ if err != nil {
+ return err
+ }
+ request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), bytes.NewReader(body))
+ if err != nil {
+ return err
+ }
+ for key, values := range headers {
+ for _, value := range values {
+ request.Header.Add(key, value)
+ }
+ }
+ request.Header.Set("Content-Type", "application/json")
+ request.Header.Set("Accept", "application/json, text/event-stream")
+ if sessionID != "" {
+ request.Header.Set("Mcp-Session-Id", sessionID)
+ }
+ response, err := client.Do(request)
+ if err != nil {
+ return err
+ }
+ defer response.Body.Close()
+ if response.StatusCode < 200 || response.StatusCode >= 300 {
+ return fmt.Errorf("remote MCP returned HTTP %d", response.StatusCode)
+ }
+ written, err := io.Copy(io.Discard, io.LimitReader(response.Body, MaxResponseBytes+1))
+ if err != nil {
+ return err
+ }
+ if written > MaxResponseBytes {
+ return errors.New("remote MCP response exceeds size limit")
+ }
+ return nil
+}
+
+func call(ctx context.Context, client *http.Client, endpoint *url.URL, headers http.Header, sessionID string, payload any) (rpcResponse, http.Header, error) {
+ body, err := json.Marshal(payload)
+ if err != nil {
+ return rpcResponse{}, nil, err
+ }
+ request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), bytes.NewReader(body))
+ if err != nil {
+ return rpcResponse{}, nil, err
+ }
+ for key, values := range headers {
+ for _, value := range values {
+ request.Header.Add(key, value)
+ }
+ }
+ request.Header.Set("Content-Type", "application/json")
+ request.Header.Set("Accept", "application/json, text/event-stream")
+ if sessionID != "" {
+ request.Header.Set("Mcp-Session-Id", sessionID)
+ }
+ response, err := client.Do(request)
+ if err != nil {
+ return rpcResponse{}, nil, err
+ }
+ defer response.Body.Close()
+ if response.StatusCode < 200 || response.StatusCode >= 300 {
+ return rpcResponse{}, response.Header, fmt.Errorf("remote MCP returned HTTP %d", response.StatusCode)
+ }
+ raw, err := readResponse(response)
+ if err != nil {
+ return rpcResponse{}, response.Header, err
+ }
+ var decoded rpcResponse
+ if err := json.Unmarshal(raw, &decoded); err != nil {
+ return rpcResponse{}, response.Header, fmt.Errorf("decode JSON-RPC response: %w", err)
+ }
+ if decoded.Error != nil {
+ return rpcResponse{}, response.Header, fmt.Errorf("remote MCP error %d: %s", decoded.Error.Code, decoded.Error.Message)
+ }
+ return decoded, response.Header, nil
+}
+
+func readResponse(response *http.Response) ([]byte, error) {
+ limited := io.LimitReader(response.Body, MaxResponseBytes+1)
+ if strings.HasPrefix(strings.ToLower(response.Header.Get("Content-Type")), "text/event-stream") {
+ scanner := bufio.NewScanner(limited)
+ scanner.Buffer(make([]byte, 4096), MaxResponseBytes+1)
+ for scanner.Scan() {
+ line := scanner.Text()
+ if strings.HasPrefix(line, "data:") {
+ data := bytes.TrimSpace([]byte(strings.TrimPrefix(line, "data:")))
+ if len(data) > 0 {
+ return data, nil
+ }
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ return nil, err
+ }
+ return nil, errors.New("remote MCP SSE response contained no data")
+ }
+ raw, err := io.ReadAll(limited)
+ if err != nil {
+ return nil, err
+ }
+ if len(raw) > MaxResponseBytes {
+ return nil, errors.New("remote MCP response exceeds size limit")
+ }
+ return raw, nil
+}
+
+func canonicalJSON(raw json.RawMessage) (json.RawMessage, error) {
+ if len(raw) == 0 {
+ raw = json.RawMessage(`{"type":"object"}`)
+ }
+ var value any
+ if err := json.Unmarshal(raw, &value); err != nil {
+ return nil, err
+ }
+ canonical, err := json.Marshal(value)
+ return json.RawMessage(canonical), err
+}
+
+func ToolSetDigest(tools []pluginruntime.RemoteMCPTool) (string, error) {
+ copyTools := append([]pluginruntime.RemoteMCPTool(nil), tools...)
+ for i := range copyTools {
+ canonical, err := canonicalJSON(copyTools[i].InputSchema)
+ if err != nil {
+ return "", fmt.Errorf("tool %q input schema: %w", copyTools[i].Name, err)
+ }
+ copyTools[i].InputSchema = canonical
+ }
+ sort.Slice(copyTools, func(i, j int) bool { return copyTools[i].Name < copyTools[j].Name })
+ raw, err := json.Marshal(copyTools)
+ if err != nil {
+ return "", err
+ }
+ return plugincontract.DigestBytes(raw), nil
+}
diff --git a/server/pkg/remotemcp/client_test.go b/server/pkg/remotemcp/client_test.go
new file mode 100644
index 0000000000..33347603a6
--- /dev/null
+++ b/server/pkg/remotemcp/client_test.go
@@ -0,0 +1,86 @@
+package remotemcp
+
+import (
+ "context"
+ "encoding/json"
+ "net/netip"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+ "github.com/multica-ai/multica/server/pkg/pluginruntime"
+)
+
+type staticResolver map[string][]netip.Addr
+
+func (r staticResolver) LookupNetIP(_ context.Context, _, host string) ([]netip.Addr, error) {
+ return r[host], nil
+}
+
+func TestValidatePublicHTTPSEndpoint(t *testing.T) {
+ resolver := staticResolver{
+ "mcp.example.com": {netip.MustParseAddr("8.8.8.8")},
+ "private.example": {netip.MustParseAddr("169.254.169.254")},
+ }
+ endpoint, err := ValidatePublicHTTPSEndpoint(context.Background(), "https://mcp.example.com/v1/mcp", []string{"mcp.example.com"}, resolver)
+ if err != nil || endpoint.Hostname() != "mcp.example.com" {
+ t.Fatalf("ValidatePublicHTTPSEndpoint = %v, %v", endpoint, err)
+ }
+ for _, raw := range []string{
+ "http://mcp.example.com/mcp",
+ "https://localhost/mcp",
+ "https://[email protected]/mcp",
+ "https://private.example/mcp",
+ } {
+ if _, err := ValidatePublicHTTPSEndpoint(context.Background(), raw, nil, resolver); err == nil {
+ t.Fatalf("endpoint %q was accepted", raw)
+ }
+ }
+ if _, err := ValidatePublicHTTPSEndpoint(context.Background(), "https://mcp.example.com/mcp", []string{"other.example.com"}, resolver); err == nil || !strings.Contains(err.Error(), "policy") {
+ t.Fatalf("host policy error = %v", err)
+ }
+}
+
+func TestHostAllowedWildcardDoesNotMatchApex(t *testing.T) {
+ if !hostAllowed("tools.example.com", []string{"*.example.com"}) {
+ t.Fatal("wildcard did not match subdomain")
+ }
+ if hostAllowed("example.com", []string{"*.example.com"}) {
+ t.Fatal("wildcard matched apex")
+ }
+}
+
+func TestContainsProtocolVersion(t *testing.T) {
+ if !containsString([]string{"2025-03-26", "2024-11-05"}, "2024-11-05") {
+ t.Fatal("declared protocol version was not found")
+ }
+ if containsString([]string{"2024-11-05"}, "2025-03-26") {
+ t.Fatal("undeclared protocol version was accepted")
+ }
+}
+
+func TestToolSetDigestIgnoresInputSchemaObjectKeyOrder(t *testing.T) {
+ firstSchema := json.RawMessage(`{"type":"object","properties":{"query":{"type":"string"},"count":{"type":"number"}}}`)
+ secondSchema := json.RawMessage(`{"properties":{"count":{"type":"number"},"query":{"type":"string"}},"type":"object"}`)
+ canonical, err := canonicalJSON(firstSchema)
+ if err != nil {
+ t.Fatal(err)
+ }
+ schemaDigest := plugincontract.DigestBytes(canonical)
+
+ first, err := ToolSetDigest([]pluginruntime.RemoteMCPTool{{
+ Name: "search", InputSchema: firstSchema, SchemaDigest: schemaDigest, Risk: "read",
+ }})
+ if err != nil {
+ t.Fatal(err)
+ }
+ second, err := ToolSetDigest([]pluginruntime.RemoteMCPTool{{
+ Name: "search", InputSchema: secondSchema, SchemaDigest: schemaDigest, Risk: "read",
+ }})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if first != second {
+ t.Fatalf("digest depends on input schema object key order: %s != %s", first, second)
+ }
+}
diff --git a/server/pkg/remotemcp/oauth.go b/server/pkg/remotemcp/oauth.go
new file mode 100644
index 0000000000..0d2cfafb19
--- /dev/null
+++ b/server/pkg/remotemcp/oauth.go
@@ -0,0 +1,383 @@
+package remotemcp
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+ "time"
+)
+
+const maxOAuthResponseBytes = 1 << 20
+
+var resourceMetadataParameter = regexp.MustCompile(`(?i)(?:^|[, ]+)resource_metadata="([^"]+)"`)
+
+// OAuthMetadata is the safe, public part of an MCP OAuth discovery result.
+// Tokens and client secrets never enter this value.
+type OAuthMetadata struct {
+ ResourceEndpoint string
+ AuthorizationEndpoint string
+ TokenEndpoint string
+ RegistrationEndpoint string
+ Scopes []string
+ TokenAuthMethods []string
+}
+
+type OAuthClientRegistration struct {
+ ClientID string
+ ClientSecret string
+ TokenEndpointAuthMethod string
+}
+
+type OAuthTokenResponse struct {
+ AccessToken string
+ TokenType string
+ ExpiresIn int64
+ RefreshToken string
+ Scope string
+}
+
+// ValidateOAuthMetadata applies the same SSRF boundary to operator-supplied
+// advanced overrides as to discovered metadata.
+func ValidateOAuthMetadata(ctx context.Context, metadata OAuthMetadata) error {
+ if metadata.AuthorizationEndpoint == "" || metadata.TokenEndpoint == "" {
+ return errors.New("OAuth metadata is missing required endpoints")
+ }
+ for _, raw := range []string{metadata.AuthorizationEndpoint, metadata.TokenEndpoint, metadata.RegistrationEndpoint} {
+ if raw == "" {
+ continue
+ }
+ if _, err := validateOAuthURL(ctx, raw); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+type protectedResourceMetadata struct {
+ Resource string `json:"resource"`
+ AuthorizationServers []string `json:"authorization_servers"`
+ ScopesSupported []string `json:"scopes_supported"`
+}
+
+type authorizationServerMetadata struct {
+ AuthorizationEndpoint string `json:"authorization_endpoint"`
+ TokenEndpoint string `json:"token_endpoint"`
+ RegistrationEndpoint string `json:"registration_endpoint"`
+ CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"`
+ TokenEndpointAuthMethodsSupport []string `json:"token_endpoint_auth_methods_supported"`
+}
+
+// DiscoverOAuth follows the MCP authorization discovery chain: a protected
+// resource metadata document (RFC 9728), then OAuth authorization-server
+// metadata (RFC 8414, with OIDC discovery as a compatibility fallback).
+// Every fetched URL is independently checked as public HTTPS and every client
+// disables proxies and cross-host redirects.
+func DiscoverOAuth(ctx context.Context, rawEndpoint string, allowedHosts []string) (OAuthMetadata, error) {
+ endpoint, err := ValidatePublicHTTPSEndpoint(ctx, rawEndpoint, allowedHosts, nil)
+ if err != nil {
+ return OAuthMetadata{}, err
+ }
+ metadataURL := probeResourceMetadataURL(ctx, endpoint)
+ if metadataURL == "" {
+ metadataURL = protectedResourceMetadataURL(endpoint)
+ }
+ resourceURL, err := validateOAuthURL(ctx, metadataURL)
+ if err != nil {
+ return OAuthMetadata{}, fmt.Errorf("protected resource metadata URL: %w", err)
+ }
+ var resource protectedResourceMetadata
+ if err := getOAuthJSON(ctx, resourceURL, &resource); err != nil {
+ return OAuthMetadata{}, fmt.Errorf("load protected resource metadata: %w", err)
+ }
+ if resource.Resource != "" && resource.Resource != endpoint.String() {
+ return OAuthMetadata{}, errors.New("protected resource metadata does not match the MCP endpoint")
+ }
+ if len(resource.AuthorizationServers) == 0 {
+ return OAuthMetadata{}, errors.New("protected resource metadata does not advertise an authorization server")
+ }
+
+ issuer, err := validateOAuthURL(ctx, resource.AuthorizationServers[0])
+ if err != nil {
+ return OAuthMetadata{}, fmt.Errorf("authorization server: %w", err)
+ }
+ var server authorizationServerMetadata
+ var discoveryErr error
+ for _, candidate := range authorizationMetadataURLs(issuer) {
+ candidateURL, validateErr := validateOAuthURL(ctx, candidate)
+ if validateErr != nil {
+ discoveryErr = validateErr
+ continue
+ }
+ if loadErr := getOAuthJSON(ctx, candidateURL, &server); loadErr == nil {
+ discoveryErr = nil
+ break
+ } else {
+ discoveryErr = loadErr
+ }
+ }
+ if discoveryErr != nil {
+ return OAuthMetadata{}, fmt.Errorf("load authorization server metadata: %w", discoveryErr)
+ }
+ if server.AuthorizationEndpoint == "" || server.TokenEndpoint == "" {
+ return OAuthMetadata{}, errors.New("authorization server metadata is missing required endpoints")
+ }
+ if len(server.CodeChallengeMethodsSupported) > 0 && !containsString(server.CodeChallengeMethodsSupported, "S256") {
+ return OAuthMetadata{}, errors.New("authorization server does not support PKCE S256")
+ }
+ metadata := OAuthMetadata{
+ ResourceEndpoint: endpoint.String(),
+ AuthorizationEndpoint: server.AuthorizationEndpoint,
+ TokenEndpoint: server.TokenEndpoint,
+ RegistrationEndpoint: server.RegistrationEndpoint,
+ Scopes: append([]string(nil), resource.ScopesSupported...),
+ TokenAuthMethods: append([]string(nil), server.TokenEndpointAuthMethodsSupport...),
+ }
+ if err := ValidateOAuthMetadata(ctx, metadata); err != nil {
+ return OAuthMetadata{}, fmt.Errorf("authorization server endpoint: %w", err)
+ }
+ return metadata, nil
+}
+
+func probeResourceMetadataURL(ctx context.Context, endpoint *url.URL) string {
+ payload := []byte(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"multica-oauth-discovery","version":"1"}}}`)
+ request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), bytes.NewReader(payload))
+ if err != nil {
+ return ""
+ }
+ request.Header.Set("Content-Type", "application/json")
+ request.Header.Set("Accept", "application/json, text/event-stream")
+ response, err := NewSecureHTTPClient(endpoint).Do(request)
+ if err != nil {
+ return ""
+ }
+ defer response.Body.Close()
+ _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, maxOAuthResponseBytes))
+ for _, challenge := range response.Header.Values("WWW-Authenticate") {
+ match := resourceMetadataParameter.FindStringSubmatch(challenge)
+ if len(match) == 2 {
+ return match[1]
+ }
+ }
+ return ""
+}
+
+func protectedResourceMetadataURL(resource *url.URL) string {
+ result := *resource
+ path := strings.TrimSuffix(resource.EscapedPath(), "/")
+ if path == "" {
+ path = "/"
+ }
+ if path == "/" {
+ result.Path = "/.well-known/oauth-protected-resource"
+ } else {
+ result.Path = "/.well-known/oauth-protected-resource" + path
+ }
+ result.RawPath = ""
+ result.RawQuery = ""
+ result.Fragment = ""
+ return result.String()
+}
+
+func authorizationMetadataURLs(issuer *url.URL) []string {
+ path := strings.TrimSuffix(issuer.EscapedPath(), "/")
+ result := make([]string, 0, 2)
+ for _, wellKnown := range []string{"oauth-authorization-server", "openid-configuration"} {
+ candidate := *issuer
+ candidate.Path = "/.well-known/" + wellKnown + path
+ candidate.RawPath = ""
+ candidate.RawQuery = ""
+ candidate.Fragment = ""
+ result = append(result, candidate.String())
+ }
+ return result
+}
+
+func validateOAuthURL(ctx context.Context, raw string) (*url.URL, error) {
+ parsed, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil || parsed.Scheme != "https" || parsed.Hostname() == "" || parsed.User != nil || parsed.Fragment != "" {
+ return nil, errors.New("URL must be public HTTPS without userinfo or fragment")
+ }
+ check := *parsed
+ check.RawQuery = ""
+ if _, err := ValidatePublicHTTPSEndpoint(ctx, check.String(), nil, nil); err != nil {
+ return nil, err
+ }
+ return parsed, nil
+}
+
+func getOAuthJSON(ctx context.Context, endpoint *url.URL, target any) error {
+ request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
+ if err != nil {
+ return err
+ }
+ request.Header.Set("Accept", "application/json")
+ return doOAuthJSON(NewSecureHTTPClient(endpoint), request, target)
+}
+
+func doOAuthJSON(client *http.Client, request *http.Request, target any) error {
+ response, err := client.Do(request)
+ if err != nil {
+ return err
+ }
+ defer response.Body.Close()
+ if response.StatusCode < 200 || response.StatusCode >= 300 {
+ _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, maxOAuthResponseBytes))
+ return fmt.Errorf("HTTP %d", response.StatusCode)
+ }
+ raw, err := io.ReadAll(io.LimitReader(response.Body, maxOAuthResponseBytes+1))
+ if err != nil {
+ return err
+ }
+ if len(raw) > maxOAuthResponseBytes {
+ return errors.New("OAuth response exceeds size limit")
+ }
+ if err := json.Unmarshal(raw, target); err != nil {
+ return err
+ }
+ return nil
+}
+
+// RegisterOAuthClient uses RFC 7591 dynamic client registration. A server
+// without a registration endpoint can still be connected through the advanced
+// path by supplying a pre-registered client id.
+func RegisterOAuthClient(ctx context.Context, metadata OAuthMetadata, redirectURI string) (OAuthClientRegistration, error) {
+ if metadata.RegistrationEndpoint == "" {
+ return OAuthClientRegistration{}, errors.New("authorization server requires a pre-registered OAuth client")
+ }
+ endpoint, err := validateOAuthURL(ctx, metadata.RegistrationEndpoint)
+ if err != nil {
+ return OAuthClientRegistration{}, err
+ }
+ body, _ := json.Marshal(map[string]any{
+ "client_name": "Multica",
+ "redirect_uris": []string{redirectURI},
+ "grant_types": []string{"authorization_code", "refresh_token"},
+ "response_types": []string{"code"},
+ "token_endpoint_auth_method": "none",
+ })
+ request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), bytes.NewReader(body))
+ if err != nil {
+ return OAuthClientRegistration{}, err
+ }
+ request.Header.Set("Content-Type", "application/json")
+ request.Header.Set("Accept", "application/json")
+ var response struct {
+ ClientID string `json:"client_id"`
+ ClientSecret string `json:"client_secret"`
+ TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
+ }
+ if err := doOAuthJSON(NewSecureHTTPClient(endpoint), request, &response); err != nil {
+ return OAuthClientRegistration{}, fmt.Errorf("dynamic client registration: %w", err)
+ }
+ if strings.TrimSpace(response.ClientID) == "" {
+ return OAuthClientRegistration{}, errors.New("dynamic client registration returned no client id")
+ }
+ if response.TokenEndpointAuthMethod == "" {
+ response.TokenEndpointAuthMethod = "none"
+ }
+ return OAuthClientRegistration(response), nil
+}
+
+func BuildAuthorizationURL(metadata OAuthMetadata, registration OAuthClientRegistration, redirectURI, state, verifier, scope string) (string, error) {
+ endpoint, err := url.Parse(metadata.AuthorizationEndpoint)
+ if err != nil {
+ return "", err
+ }
+ challenge := sha256.Sum256([]byte(verifier))
+ query := endpoint.Query()
+ query.Set("response_type", "code")
+ query.Set("client_id", registration.ClientID)
+ query.Set("redirect_uri", redirectURI)
+ query.Set("state", state)
+ query.Set("code_challenge", base64.RawURLEncoding.EncodeToString(challenge[:]))
+ query.Set("code_challenge_method", "S256")
+ query.Set("resource", metadata.ResourceEndpoint)
+ if strings.TrimSpace(scope) != "" {
+ query.Set("scope", strings.TrimSpace(scope))
+ }
+ endpoint.RawQuery = query.Encode()
+ return endpoint.String(), nil
+}
+
+func ExchangeOAuthCode(ctx context.Context, tokenEndpoint, resource, code, redirectURI, verifier string, registration OAuthClientRegistration) (OAuthTokenResponse, error) {
+ values := url.Values{
+ "grant_type": {"authorization_code"},
+ "code": {code},
+ "redirect_uri": {redirectURI},
+ "client_id": {registration.ClientID},
+ "code_verifier": {verifier},
+ "resource": {resource},
+ }
+ return requestOAuthToken(ctx, tokenEndpoint, values, registration)
+}
+
+func RefreshOAuthToken(ctx context.Context, tokenEndpoint, resource, refreshToken string, registration OAuthClientRegistration) (OAuthTokenResponse, error) {
+ values := url.Values{
+ "grant_type": {"refresh_token"},
+ "refresh_token": {refreshToken},
+ "client_id": {registration.ClientID},
+ "resource": {resource},
+ }
+ return requestOAuthToken(ctx, tokenEndpoint, values, registration)
+}
+
+func requestOAuthToken(ctx context.Context, rawEndpoint string, values url.Values, registration OAuthClientRegistration) (OAuthTokenResponse, error) {
+ endpoint, err := validateOAuthURL(ctx, rawEndpoint)
+ if err != nil {
+ return OAuthTokenResponse{}, err
+ }
+ if registration.ClientSecret != "" && registration.TokenEndpointAuthMethod == "client_secret_post" {
+ values.Set("client_secret", registration.ClientSecret)
+ }
+ request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), strings.NewReader(values.Encode()))
+ if err != nil {
+ return OAuthTokenResponse{}, err
+ }
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ request.Header.Set("Accept", "application/json")
+ if registration.ClientSecret != "" && registration.TokenEndpointAuthMethod == "client_secret_basic" {
+ request.SetBasicAuth(registration.ClientID, registration.ClientSecret)
+ }
+ var response struct {
+ AccessToken string `json:"access_token"`
+ TokenType string `json:"token_type"`
+ ExpiresIn json.RawMessage `json:"expires_in"`
+ RefreshToken string `json:"refresh_token"`
+ Scope string `json:"scope"`
+ }
+ if err := doOAuthJSON(NewSecureHTTPClient(endpoint), request, &response); err != nil {
+ return OAuthTokenResponse{}, err
+ }
+ if response.AccessToken == "" || !strings.EqualFold(response.TokenType, "Bearer") {
+ return OAuthTokenResponse{}, errors.New("token endpoint did not return a Bearer access token")
+ }
+ expiresIn := int64(0)
+ if len(response.ExpiresIn) > 0 {
+ if err := json.Unmarshal(response.ExpiresIn, &expiresIn); err != nil {
+ var text string
+ if json.Unmarshal(response.ExpiresIn, &text) == nil {
+ _, _ = fmt.Sscan(text, &expiresIn)
+ }
+ }
+ }
+ return OAuthTokenResponse{
+ AccessToken: response.AccessToken, TokenType: "Bearer", ExpiresIn: expiresIn,
+ RefreshToken: response.RefreshToken, Scope: response.Scope,
+ }, nil
+}
+
+func OAuthExpiry(now time.Time, expiresIn int64) time.Time {
+ if expiresIn <= 0 {
+ return time.Time{}
+ }
+ return now.Add(time.Duration(expiresIn) * time.Second)
+}
diff --git a/server/pkg/remotemcp/oauth_test.go b/server/pkg/remotemcp/oauth_test.go
new file mode 100644
index 0000000000..6de371ade0
--- /dev/null
+++ b/server/pkg/remotemcp/oauth_test.go
@@ -0,0 +1,68 @@
+package remotemcp
+
+import (
+ "crypto/sha256"
+ "encoding/base64"
+ "net/url"
+ "testing"
+)
+
+func TestProtectedResourceMetadataURLPreservesResourcePath(t *testing.T) {
+ resource, _ := url.Parse("https://api.example.com/mcp")
+ if got, want := protectedResourceMetadataURL(resource), "https://api.example.com/.well-known/oauth-protected-resource/mcp"; got != want {
+ t.Fatalf("protectedResourceMetadataURL = %q, want %q", got, want)
+ }
+ root, _ := url.Parse("https://api.example.com/")
+ if got, want := protectedResourceMetadataURL(root), "https://api.example.com/.well-known/oauth-protected-resource"; got != want {
+ t.Fatalf("root protectedResourceMetadataURL = %q, want %q", got, want)
+ }
+}
+
+func TestAuthorizationMetadataURLsPreserveIssuerPath(t *testing.T) {
+ issuer, _ := url.Parse("https://login.example.com/tenant")
+ got := authorizationMetadataURLs(issuer)
+ if len(got) != 2 || got[0] != "https://login.example.com/.well-known/oauth-authorization-server/tenant" || got[1] != "https://login.example.com/.well-known/openid-configuration/tenant" {
+ t.Fatalf("authorizationMetadataURLs = %#v", got)
+ }
+}
+
+func TestBuildAuthorizationURLPinsPKCEStateAndResource(t *testing.T) {
+ metadata := OAuthMetadata{
+ ResourceEndpoint: "https://api.example.com/mcp",
+ AuthorizationEndpoint: "https://login.example.com/authorize?audience=existing",
+ }
+ registration := OAuthClientRegistration{ClientID: "client-1"}
+ got, err := BuildAuthorizationURL(metadata, registration, "https://multica.example/api/callback", "state-1", "verifier-1", "search read")
+ if err != nil {
+ t.Fatal(err)
+ }
+ parsed, _ := url.Parse(got)
+ query := parsed.Query()
+ wantChallenge := sha256.Sum256([]byte("verifier-1"))
+ checks := map[string]string{
+ "audience": "existing",
+ "response_type": "code",
+ "client_id": "client-1",
+ "redirect_uri": "https://multica.example/api/callback",
+ "state": "state-1",
+ "code_challenge": base64.RawURLEncoding.EncodeToString(wantChallenge[:]),
+ "code_challenge_method": "S256",
+ "resource": "https://api.example.com/mcp",
+ "scope": "search read",
+ }
+ for key, want := range checks {
+ if value := query.Get(key); value != want {
+ t.Errorf("query %s = %q, want %q", key, value, want)
+ }
+ }
+}
+
+func TestValidateOAuthMetadataRejectsUnsafeAdvancedOverride(t *testing.T) {
+ err := ValidateOAuthMetadata(t.Context(), OAuthMetadata{
+ AuthorizationEndpoint: "http://127.0.0.1/authorize",
+ TokenEndpoint: "https://8.8.8.8/token",
+ })
+ if err == nil {
+ t.Fatal("unsafe authorization endpoint was accepted")
+ }
+}
diff --git a/server/pkg/remotemcp/remotemcptest/fixture.go b/server/pkg/remotemcp/remotemcptest/fixture.go
new file mode 100644
index 0000000000..18e414aff1
--- /dev/null
+++ b/server/pkg/remotemcp/remotemcptest/fixture.go
@@ -0,0 +1,111 @@
+// Package remotemcptest provides a deterministic MCP server for isolated
+// broker and Plugin lifecycle tests. It is deliberately not a production MCP
+// endpoint: callers own the httptest server lifecycle and no network escapes
+// the test process.
+package remotemcptest
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+)
+
+const Credential = "fixture-token"
+
+type Server struct {
+ *httptest.Server
+
+ mu sync.Mutex
+ writes []string
+}
+
+type request struct {
+ JSONRPC string `json:"jsonrpc"`
+ ID json.RawMessage `json:"id"`
+ Method string `json:"method"`
+ Params json.RawMessage `json:"params"`
+}
+
+func NewServer() *Server {
+ fixture := &Server{}
+ fixture.Server = httptest.NewServer(http.HandlerFunc(fixture.serveHTTP))
+ return fixture
+}
+
+func (fixture *Server) Writes() []string {
+ fixture.mu.Lock()
+ defer fixture.mu.Unlock()
+ return append([]string(nil), fixture.writes...)
+}
+
+func (fixture *Server) serveHTTP(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.Header.Get("Authorization") != "Bearer "+Credential {
+ w.WriteHeader(http.StatusUnauthorized)
+ _ = json.NewEncoder(w).Encode(map[string]any{"error": "credential rejected"})
+ return
+ }
+ var input request
+ if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ result := map[string]any{}
+ switch input.Method {
+ case "initialize":
+ result = map[string]any{
+ "protocolVersion": "2025-03-26",
+ "capabilities": map[string]any{"tools": map[string]any{}},
+ "serverInfo": map[string]any{"name": "multica-remote-mcp-fixture", "version": "1.0.0"},
+ }
+ case "notifications/initialized":
+ w.WriteHeader(http.StatusAccepted)
+ return
+ case "tools/list":
+ result = map[string]any{"tools": []any{
+ map[string]any{
+ "name": "fixture.read", "description": "Read a deterministic fixture value",
+ "inputSchema": map[string]any{"type": "object", "properties": map[string]any{}},
+ },
+ map[string]any{
+ "name": "fixture.write", "description": "Append a value to the fixture log",
+ "inputSchema": map[string]any{
+ "type": "object", "required": []string{"value"},
+ "properties": map[string]any{"value": map[string]any{"type": "string"}},
+ },
+ },
+ }}
+ case "tools/call":
+ var params struct {
+ Name string `json:"name"`
+ Arguments struct {
+ Value string `json:"value"`
+ } `json:"arguments"`
+ }
+ _ = json.Unmarshal(input.Params, &params)
+ switch params.Name {
+ case "fixture.read":
+ result = map[string]any{"content": []any{map[string]any{"type": "text", "text": "fixture-value"}}}
+ case "fixture.write":
+ fixture.mu.Lock()
+ fixture.writes = append(fixture.writes, params.Arguments.Value)
+ fixture.mu.Unlock()
+ result = map[string]any{"content": []any{map[string]any{"type": "text", "text": "written"}}}
+ default:
+ writeError(w, input.ID, -32602, "unknown tool")
+ return
+ }
+ default:
+ writeError(w, input.ID, -32601, "method not found")
+ return
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": input.ID, "result": result})
+}
+
+func writeError(w http.ResponseWriter, id json.RawMessage, code int, message string) {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "jsonrpc": "2.0", "id": id,
+ "error": map[string]any{"code": code, "message": message},
+ })
+}
diff --git a/server/pkg/remotemcp/remotemcptest/fixture_test.go b/server/pkg/remotemcp/remotemcptest/fixture_test.go
new file mode 100644
index 0000000000..b75bb3fdba
--- /dev/null
+++ b/server/pkg/remotemcp/remotemcptest/fixture_test.go
@@ -0,0 +1,42 @@
+package remotemcptest
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "testing"
+)
+
+func TestFixtureExposesReadAndSideEffectingWrite(t *testing.T) {
+ fixture := NewServer()
+ defer fixture.Close()
+
+ call := func(method, params string) map[string]any {
+ t.Helper()
+ body := []byte(`{"jsonrpc":"2.0","id":1,"method":"` + method + `","params":` + params + `}`)
+ request, err := http.NewRequest(http.MethodPost, fixture.URL, bytes.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ request.Header.Set("Authorization", "Bearer "+Credential)
+ response, err := http.DefaultClient.Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ var decoded map[string]any
+ if err := json.NewDecoder(response.Body).Decode(&decoded); err != nil {
+ t.Fatal(err)
+ }
+ return decoded
+ }
+
+ listed := call("tools/list", `{}`)
+ if listed["result"] == nil {
+ t.Fatalf("tools/list = %#v", listed)
+ }
+ call("tools/call", `{"name":"fixture.write","arguments":{"value":"one"}}`)
+ if writes := fixture.Writes(); len(writes) != 1 || writes[0] != "one" {
+ t.Fatalf("writes = %#v", writes)
+ }
+}