Files
multica/server/internal/handler/plugin_mcp.go
4bf3c73a15 feat(plugins): agent integration — skill resources, agent trigger, mcp transport (MUL-6350 PR 4) (#7242)
* feat(plugins): skill resources into the existing skill table (MUL-6350 PR 4, 1/3)

A plugin's skill resource becomes an ordinary row in the skill table. Not a
plugin-owned copy, not a bundle, not an artifact with a digest: the previous
plugin system built all of that across fourteen tables and, at the end of it,
delivered one SKILL.md that this table could already hold.

The only thing the platform has to remember is which installation contributed
which skill, so uninstall removes exactly those and nothing a person wrote.
That is one nullable column.

The upsert is scoped to rows this installation owns, so a plugin claiming a
name somebody already used fails the install instead of silently replacing
their work — and the test asserts the human's content survives. Upgrade prunes
what the new manifest no longer declares, or a renamed skill would leave its
predecessor behind with nothing to attribute it to.

Fresh install is now a transaction too. It was a single INSERT; skills have to
land in the same commit, because an installation whose skills half-arrived is
worse than one that failed — the missing half is invisible.

Skill resources flip on here rather than with the rest of PR 4: nothing
executes, so it does not wait for the daemon-side MCP server that the agent
trigger and mcp transport still need.

Co-authored-by: multica-agent <[email protected]>

* feat(plugins): agent trigger — hooks as MCP tools (MUL-6350 PR 4, 2/3)

The fourth call site, and the only one that is not the host deciding to call
something: an agent reads a tool description and chooses. That choice is why
hooks may be reached from an agent at all — the alternative, a hook that must
run before or after every turn, is a third party holding the product's main
loop open, and no such position exists anywhere in this design.

The daemon renders the tools but does not call the plugin. A tool call goes
back to Multica, which makes the signed request. Two reasons, and the second
matters more: the signing secret is derived from the deployment key and putting
it on every laptop running an agent would hand out a credential that can
impersonate the server to every plugin backend; and routing through the server
keeps the rate limit, circuit breaker, `net:` destination check and invocation
record on one code path for all four triggers instead of a daemon-side copy
that would drift.

A failing hook is a TOOL error, not a transport error. The agent reads it,
works around it, and finishes the issue — an unreachable plugin endpoint must
not fail somebody's task. The server returns 200 with a status for the same
reason: a non-2xx would look to the daemon like the broker itself is broken.

TestPluginToolNameSeparatorCannotBeForged caught a real flaw in my first
naming scheme. Sanitizing both halves and joining with an underscore is not
injective — a plugin key uses `.` and `-`, both of which have to become `_`, so
`a.b` and `a-b` collapse together and `a.b_` + `c` collides with `a.b` + `c`.
Two plugins would have been offering the agent one tool name. The prefix now
carries a short digest of the full key rather than a lossy transliteration.

Co-authored-by: multica-agent <[email protected]>

* feat(plugins): mcp transport with pinned tool approval (MUL-6350 PR 4, 3/3)

An `mcp` hook adopts tools from an MCP server the plugin author already runs.
The difference from an `http` hook is who decides the shape: an http hook
declares one endpoint in a manifest an administrator read, while an MCP server
decides its own tool list at runtime. So installing the plugin is not the grant
— an administrator discovers the tools and pins a specific set by name and
schema digest, and a tool that appears later is not adopted until approved.

Approved hooks reach the daemon as ordinary remotemcp.Connection values, so the
existing broker proxies them and validatePinnedRemoteMCPTools already refuses to
start when an approved tool went missing or its schema drifted. No new
enforcement path.

Plugin connections carry a `plugin:` contribution-id prefix. They share the
broker and the resolver with a workspace's own Remote MCP connections but keep
their credential in the Plugin's secret storage, which a different route serves,
and the contribution id is all the broker hands back at dial time.

Flips TransportMCP on in HostCapabilities, completing PR 4's capability set.

Co-authored-by: multica-agent <[email protected]>

* test(plugins): cover mcp connection startup via the dev-origin seam

The `http` transport has had MULTICA_PLUGIN_DEV_ORIGINS since the hook engine
landed: an operator names exact origins, and endpoints there skip the
public-internet requirement so a plugin author can develop against a server on
their own machine. The `mcp` transport never got it.

Two symptoms, one cause. A plugin author could not point an mcp hook at a local
MCP server, and — for the same reason — the daemon's connection startup could
not be reached by a test, because it validates the endpoint as public HTTPS and
the repo's MCP fixture serves plain HTTP on loopback. That left the layer
carrying the entire approval guarantee at 0% coverage:

  startTaskRemoteMCPBrokers      0.0% -> 59.5%
  validatePinnedRemoteMCPTools   0.0% -> 100.0%

The seam is off unless the variable is set, and a test asserts that: the same
loopback connection is refused when it is empty. It skips only the
public-internet requirement — the net: scope still applies, and the dial-time
host pin still refuses a redirect that changes host.

Tests cover what the approval is for: an approved tool the server dropped, an
approved tool whose schema drifted, and an optional connection that fails
without failing the task. Each was verified by breaking the guard it covers.

Co-authored-by: multica-agent <[email protected]>

* feat(plugins): a real example plugin, and the two bugs it found

examples/plugins/deploy-sentinel is an incident-response plugin: it correlates
an issue with recent deploys, files rollback requests under the team's own rules
(refusing deploys past a window, and reasons too short to be evidence), pages
on-call on issue events, and adopts an external metrics MCP server. Four
triggers, both transports, and a skill that tells an agent when to use any of it.

The other examples each demonstrate one mechanism. This one was written to find
out whether the mechanisms compose, and it found two things that no unit test
was ever going to:

1. mcp discovery could not succeed against ANY server. DiscoverMCPHookTools
   passed a nil protocol-version list, and Discover checks the server's answer
   against that same slice — empty means nothing is acceptable. Discover now
   falls back to SupportedProtocolVersions() when the caller passes none.

2. A hook handler had no way to read its own configuration. The manifest's
   config block drives a host-rendered form, the Action API has no config
   endpoint, and the hook body did not carry the values — so a plugin would have
   had to keep a second copy on its own server. The body now carries non-secret
   config. Secret-typed fields are excluded; they live in a separate table and
   are the plugin's credentials for its own services.

Also lets an mcp dev origin trust MULTICA_PLUGIN_DEV_CA, mirroring the http
transport. The manifest validator requires HTTPS, so without this a local MCP
server could not be developed against at all.

plugin_example_test.go installs the real manifest from examples/, not a copy, so
a broken example fails the build rather than rotting quietly.

Migrations renumbered to 368/369 after main advanced. 362 is added to the
legacy-duplicate allowlist: two PRs took that prefix within the same hour and
both merged, and the ledger keys on the full stem, so renaming one would re-run
it everywhere it has already applied. main is red on this today.

Co-authored-by: multica-agent <[email protected]>

* fix(plugins): the deploy-sentinel example servers must serve HTTPS

Both .mjs servers used node:http. A hook's transport URL has to be an https://
URL or the manifest fails validation, so the example as shipped could not
actually be installed against a running Multica — the README told you to set
MULTICA_PLUGIN_DEV_ORIGINS to https:// origins that nothing was listening on.

Found by running it: install, config, skill contribution and live MCP tool
discovery all work against the real servers once they speak TLS. They read
TLS_CERT / TLS_KEY and the README carries the openssl one-liner.

MULTICA_PLUGIN_DEV_CA changes which certificate is trusted; it never disables
verification, which is why a self-signed certificate is needed rather than
plain HTTP.

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Lambda <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-08-20 02:35:29 +08:00

160 lines
5.4 KiB
Go

package handler
import (
"encoding/json"
"net/http"
"strings"
"github.com/go-chi/chi/v5"
"github.com/multica-ai/multica/server/pkg/remotemcp"
)
// Admin approval for an mcp-transport hook.
//
// Discovery is read-only and adopts nothing. Approval is the grant, and it pins
// the tools by schema digest — because an MCP server, unlike an http endpoint,
// decides its own tool list at runtime and can change it after the
// administrator read the manifest.
type pluginMCPToolResponse struct {
Name string `json:"name"`
Description string `json:"description"`
SchemaDigest string `json:"schema_digest"`
Approved bool `json:"approved"`
// Drifted marks a tool that IS approved but whose schema no longer matches.
// Surfaced rather than silently re-approved: the administrator approved a
// specific shape, and a changed one is a new decision.
Drifted bool `json:"drifted,omitempty"`
}
// ListPluginMCPTools — GET /api/workspaces/{id}/plugins/{installationId}/mcp/{hookKey}/tools
func (h *Handler) ListPluginMCPTools(w http.ResponseWriter, r *http.Request) {
installation, ok := h.pluginInstallationFromURL(w, r)
if !ok {
return
}
hookKey := chi.URLParam(r, "hookKey")
discovered, err := h.PluginService.DiscoverMCPHookTools(r.Context(), installation, hookKey)
if err != nil {
writePluginError(w, err, "failed to reach the Plugin's MCP server")
return
}
approved := h.PluginService.ApprovedMCPTools(installation, hookKey)
items := make([]pluginMCPToolResponse, 0, len(discovered))
for _, tool := range discovered {
pinned, isApproved := approved[tool.Name]
items = append(items, pluginMCPToolResponse{
Name: tool.Name,
Description: tool.Description,
SchemaDigest: tool.SchemaDigest,
Approved: isApproved,
Drifted: isApproved && pinned.SchemaDigest != tool.SchemaDigest,
})
}
writeJSON(w, http.StatusOK, map[string]any{"tools": items})
}
type approvePluginMCPToolsRequest struct {
// Tools is the complete approved set, not a delta. An administrator
// removing one is the same request shape as adding one, so there is no way
// to think you revoked something and have it stay.
Tools []string `json:"tools"`
}
// ApprovePluginMCPTools — PUT /api/workspaces/{id}/plugins/{installationId}/mcp/{hookKey}/tools
func (h *Handler) ApprovePluginMCPTools(w http.ResponseWriter, r *http.Request) {
installation, ok := h.pluginInstallationFromURL(w, r)
if !ok {
return
}
userID, ok := requireUserID(w, r)
if !ok {
return
}
parsedUserID, ok := parseUUIDOrBadRequest(w, userID, "user_id")
if !ok {
return
}
var req approvePluginMCPToolsRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
updated, err := h.PluginService.ApproveMCPHookTools(
r.Context(), installation, chi.URLParam(r, "hookKey"), req.Tools, parsedUserID)
if err != nil {
writePluginError(w, err, "failed to approve the MCP tools")
return
}
payload, err := h.pluginInstallationPayload(r.Context(), updated)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to load the Plugin")
return
}
writeJSON(w, http.StatusOK, payload)
}
// splitPluginContributionID reads back the
// "plugin:<installation uuid>:<hook key>" id AgentMCPConnections built.
//
// The prefix is required, not tolerated: it is what distinguishes a Plugin
// contribution from a workspace's own Remote MCP connection, and those resolve
// their credentials from entirely different places. Both halves after it must
// be present too — a bare installation id would otherwise resolve to an empty
// hook key, and an empty installation id to whatever the workspace lookup makes
// of "", so a daemon holding one contribution's id could name another by
// trimming the string.
func splitPluginContributionID(contribution string) (string, string, bool) {
trimmed, hasPrefix := strings.CutPrefix(contribution, remotemcp.PluginContributionPrefix)
if !hasPrefix {
return "", "", false
}
installationID, hookKey, found := strings.Cut(trimmed, ":")
if !found || installationID == "" || hookKey == "" {
return "", "", false
}
return installationID, hookKey, true
}
// ResolvePluginMCPCredential — GET /api/daemon/tasks/{id}/plugin-mcp/{contributionId}/credential
//
// The daemon's broker asks for the credential at connection time rather than
// receiving it in the claim payload, so a secret never sits in a task record.
// Authenticated as the daemon and scoped to a claimed task, like every other
// /api/daemon route.
func (h *Handler) ResolvePluginMCPCredential(w http.ResponseWriter, r *http.Request) {
if !h.requirePluginsV1(w, r) {
return
}
_, workspaceID, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, chi.URLParam(r, "id"))
if !ok {
return
}
installationID, hookKey, ok := splitPluginContributionID(chi.URLParam(r, "contributionId"))
if !ok {
writeError(w, http.StatusBadRequest, "malformed contribution id")
return
}
installation, err := h.PluginService.InstallationForWorkspace(r.Context(), parseUUID(workspaceID), installationID)
if err != nil {
writePluginError(w, err, "failed to load the Plugin")
return
}
header, credential, err := h.PluginService.MCPHookCredential(r.Context(), installation, hookKey)
if err != nil {
writePluginError(w, err, "failed to resolve the credential")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"credential_header": header,
"credential": credential,
})
}