{"modulePath":"github.com/memcode-ai/memcode","version":"v0.56.16","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package mcp\n\nPackage mcp gives memcode an MCP (Model Context Protocol) client: it discovers the servers configured across scopes (local / project / user), connects to them (stdio, streamable HTTP, or SSE), lists their tools, and exposes a single Call entrypoint. This is the same mechanism Claude Code uses to gain third-party tools — and it follows Claude Code's documented model: project-scoped servers live in a checked-in .mcp.json and require explicit approval before use (see approvals.go), while servers you add yourself (local / user scope, in ~/.memcode/mcp.json) are trusted.\n\nThe protocol itself is spoken by the official SDK (github.com/modelcontextprotocol/go-sdk); this package handles config, scopes, approval, lifecycle, namespacing, and result flattening. The permission gate on each CALL lives in the runtime package (runtime/mcp.go).\n\n## Functions\n\n```go\nfunc AddServer(root string, scope Scope, name string, sc ServerConfig) error\n```\nAddServer writes a server into the given scope's store (raw, unexpanded — secrets stay as ${VAR} references). Overwrites an existing entry of the same name in that scope.\n\n```go\nfunc ApprovalsPath(root string) string\n```\nApprovalsPath is where a project's MCP approval choices live: user-level state under the home directory (like UserStoreFile), keyed by a hash of the canonical project root so each project gets its own file. NEVER inside the repo — see the package header. Returns \"\" when no home directory can be determined.\n\n```go\nfunc ConfigHash(cfg ServerConfig) string\n```\nConfigHash is a stable digest of a server's RAW config (as read from its store, before ${VAR} expansion — see Resolve), so any edit to its .mcp.json entry invalidates a prior approval (re-prompting), while environment changes (which don't alter the committed config) do not — and resolved secrets never feed the hash.\n\n```go\nfunc LocalServers(root string) map[string]ServerConfig\n```\nLocalServers reads the raw local-scoped servers for this project from the user store.\n\n```go\nfunc ProjectFile(root string) string\n```\nProjectFile is the path to a project's checked-in MCP config.\n\n```go\nfunc ProjectServers(root string) map[string]ServerConfig\n```\nProjectServers reads the raw (unexpanded) project-scoped servers from \\\u003croot\u003e/.mcp.json.\n\n```go\nfunc RememberCalls(root, name string, cfg ServerConfig, rawTool string) error\n```\nRememberCalls persists an invocation grant: rawTool == \"\" remembers the whole server (\"Don't ask again for \\\u003cserver\u003e\"), otherwise the one tool (\"Execute and remember\"). For a local/user server this creates the record (those scopes are never connect-gated, so the record exists purely to carry grants); a stale-hash record is replaced, not merged.\n\n```go\nfunc RemoveServer(root string, scope Scope, name string) (bool, error)\n```\nRemoveServer deletes a named server from a scope, reporting whether it existed.\n\n```go\nfunc ResetApprovals(root string) error\n```\nResetApprovals clears all project-server choices (Claude Code's reset-project-choices). It also removes any legacy repo-resident file (ignored as a trust source, but stale).\n\n```go\nfunc SaveApproval(root, name string, cfg ServerConfig, d Decision) error\n```\nSaveApproval records a decision for a project server, hashed against its current config. A same-config re-approve keeps any invocation grants; a rejection or config change drops them.\n\n```go\nfunc ToolName(server, raw string) string\n```\nToolName builds the model-facing name for a server's tool: mcp\\_\\_\\\u003cserver\u003e\\_\\_\\\u003craw\u003e. Both segments are sanitized to the function-name charset \\[A-Za-z0-9\\_] and the whole is capped at maxToolNameLen, so NO lane rejects the request over an odd or long server/tool name. The ORIGINAL raw name is preserved in Tool.Raw and used for the actual CallTool (see Call), so a sanitized/truncated model-facing name never changes which server tool runs. When sanitizing or truncating could make two distinct raw names collide, a short stable hash of the (server,raw) pair disambiguates — keeping byName keys unique. The clean, short common case is returned verbatim (Claude Code's scheme) so familiar names like mcp\\_\\_supabase\\_\\_execute\\_sql are unchanged.\n\n```go\nfunc UserServers() map[string]ServerConfig\n```\nUserServers reads the raw user-scoped servers from the user store.\n\n```go\nfunc UserStoreFile() string\n```\nUserStoreFile is the path to the user-global MCP store (user + local scopes).\n\n## Types\n\n```go\ntype Approvals map[string]approvalRecord\n```\nApprovals is the persisted set of project-server choices for one project.\n\n```go\nfunc LoadApprovals(root string) Approvals\n```\nLoadApprovals reads the remembered choices (absent file → empty, not an error). Only the user-level store is consulted — a repo-committed approvals file grants nothing.\n\n```go\nfunc (a Approvals) CallAllowed(name string, cfg ServerConfig, rawTool string) bool\n```\nCallAllowed reports whether invoking rawTool on the named server was remembered. False the moment the config hash stops matching — grants die with the config they were made against.\n\n```go\nfunc (a Approvals) Status(name string, cfg ServerConfig) Decision\n```\nStatus reports a project server's standing given the current config: \"approved\" only when a stored approval matches the live config hash; \"rejected\" when explicitly rejected (and still matching); otherwise \"pending\" (never decided, or the config changed since).\n\n```go\ntype Decision string\n```\nDecision is a remembered approval choice for a project-scoped server.\n\n```go\nconst (\n\tApproved Decision = \"approved\"\n\tRejected Decision = \"rejected\"\n)\n```\n\n```go\ntype Manager struct {\n\t// contains filtered or unexported fields\n}\n```\nManager owns the live connections to all configured MCP servers and the merged tool catalog. A nil \\*Manager is valid and behaves as \"no MCP\" — all methods are safe to call.\n\n```go\nfunc Connect(ctx context.Context, servers map[string]ServerConfig, opts Options) *Manager\n```\nConnect connects to each given server (already resolved across scopes and filtered by approval policy — see Resolve and approvals.go), returning a Manager with the merged tool catalog. A server that fails to connect or list is skipped (recorded in Errors), never fatal — one broken server must not sink the session. Returns nil when the set is empty, so callers can treat \"no MCP\" as the zero case.\n\n```go\nfunc (m *Manager) Add(ctx context.Context, servers map[string]ServerConfig, opts Options)\n```\nAdd connects additional servers into an existing manager and merges their tools — used when a project server is approved mid-session. Safe on a nil receiver (returns it unchanged via the caller). Errors are appended to Errors(), never returned.\n\n```go\nfunc (m *Manager) Call(ctx context.Context, name string, args map[string]any) (string, bool, error)\n```\nCall invokes a namespaced MCP tool and returns its flattened text, whether the tool reported an error, and any transport error.\n\n```go\nfunc (m *Manager) Close()\n```\nClose tears down every connection. Safe on a nil Manager and idempotent.\n\n```go\nfunc (m *Manager) Errors() []error\n```\nErrors returns the per-server connect/list failures gathered during Connect.\n\n```go\nfunc (m *Manager) GetPrompt(ctx context.Context, name string, args map[string]string) (string, error)\n```\nGetPrompt renders a namespaced prompt template with args, returning the flattened message text the model can use.\n\n```go\nfunc (m *Manager) Has(name string) bool\n```\nHas reports whether name is a known MCP tool (used by the dispatcher to route a call).\n\n```go\nfunc (m *Manager) Lookup(name string) (Tool, bool)\n```\nLookup returns the catalog entry for a namespaced tool name.\n\n```go\nfunc (m *Manager) Prompts() []Prompt\n```\nPrompts returns the merged prompt catalog across all connected servers.\n\n```go\nfunc (m *Manager) ReadResource(ctx context.Context, uri string) (string, error)\n```\nReadResource fetches a resource's contents by uri, flattened to text.\n\n```go\nfunc (m *Manager) Resources() []Resource\n```\nResources returns the merged resource catalog across all connected servers.\n\n```go\nfunc (m *Manager) Tools() []Tool\n```\nTools returns the merged, namespaced tool catalog across all connected servers.\n\n```go\ntype Options struct {\n\tVersion    string // memcode version reported to servers\n\tAllowOAuth bool   // attach the interactive OAuth flow to remote servers that need auth (interactive sessions only)\n\t// Root is the project the session runs in. When set, stdio servers run\n\t// inside memcode's OS shield (internal/sandbox): a third-party server can't\n\t// read memcode's credentials or rewrite its settings.\n\tRoot string\n}\n```\nOptions configure a connection batch.\n\n```go\ntype Prompt struct {\n\tName        string // namespaced\n\tServer      string\n\tRaw         string\n\tDescription string\n\tArguments   []PromptArg\n}\n```\nPrompt is one reusable MCP prompt template a server exposes. Name is namespaced (mcp\\_\\_\\\u003cserver\u003e\\_\\_\\\u003craw\u003e) for the catalog; the raw name is used with GetPrompt.\n\n```go\ntype PromptArg struct {\n\tName        string\n\tDescription string\n\tRequired    bool\n}\n```\nPromptArg describes one argument a prompt template accepts.\n\n```go\ntype Resource struct {\n\tURI         string // the server's resource uri (what ReadResource takes)\n\tServer      string\n\tName        string\n\tDescription string\n\tMIMEType    string\n}\n```\nResource is one MCP resource exposed by a server — external context (a doc, a schema, a runbook) the model can READ by uri. Namespaced like tools so servers can't collide.\n\n```go\ntype Scope string\n```\nScope is where a server is configured, mirroring Claude Code's three scopes.\n\n```go\nconst (\n\t// ScopeLocal is private to you in ONE project (stored in ~/.memcode/mcp.json under the\n\t// project path). Trusted — you added it.\n\tScopeLocal Scope = \"local\"\n\t// ScopeProject is shared with the team via a checked-in \u003croot\u003e/.mcp.json. UNTRUSTED until\n\t// approved (see approvals.go) — it's repo content that could come from anyone.\n\tScopeProject Scope = \"project\"\n\t// ScopeUser is available across all your projects (stored in ~/.memcode/mcp.json). Trusted.\n\tScopeUser Scope = \"user\"\n)\n```\n\n```go\ntype ScopedServer struct {\n\tName   string\n\tScope  Scope\n\tConfig ServerConfig // raw (unexpanded); ExpandServer before connecting\n}\n```\nScopedServer is a server resolved with the scope that won it. Config is the RAW entry as stored (${VAR} references intact): approvals and invocation grants hash the raw config (see approvals.ConfigHash), so env changes never invalidate them and resolved secrets never feed the hash. Expand with ExpandServer at connect time.\n\n```go\nfunc Resolve(root string) []ScopedServer\n```\nResolve returns every configured server merged across scopes with Claude Code's precedence (local \u003e project \u003e user, matched by name; the whole winning entry is used, never merged), each RAW (unexpanded) and tagged with its scope. The caller applies approval policy (project scope) against the raw config and calls ExpandServer only on what it actually connects.\n\n```go\ntype ServerConfig struct {\n\tType    string            `json:\"type,omitempty\"` // stdio | http | streamable-http | sse (inferred when empty)\n\tCommand string            `json:\"command,omitempty\"`\n\tArgs    []string          `json:\"args,omitempty\"`\n\tEnv     map[string]string `json:\"env,omitempty\"`\n\tURL     string            `json:\"url,omitempty\"`\n\tHeaders map[string]string `json:\"headers,omitempty\"`\n\t// HeadersHelper is an optional command run at connect time whose stdout supplies HTTP\n\t// headers (JSON object, or \"Name: value\" lines) — for tokens minted per connection rather\n\t// than stored in config. Merged over static Headers.\n\tHeadersHelper string `json:\"headersHelper,omitempty\"`\n\t// Timeout is a per-server tool-call timeout in milliseconds (overrides the default).\n\tTimeout int `json:\"timeout,omitempty\"`\n\t// Auth controls remote authentication: \"\" / \"auto\" attaches the interactive OAuth flow when\n\t// no static auth header is present; \"oauth\" forces it; \"none\" disables it.\n\tAuth string `json:\"auth,omitempty\"`\n}\n```\nServerConfig is one declared MCP server. A stdio server is launched as a subprocess (Command+Args+Env); an http/sse server is reached at URL with optional Headers.\n\n```go\nfunc ExpandServer(sc ServerConfig) ServerConfig\n```\nExpandServer expands ${VAR} / ${VAR:-default} in every string the config carries — so a secret like an access token lives in the environment, not committed in .mcp.json. Callers expand at CONNECT time only; approvals/grants always hash the raw config (ConfigHash).\n\n```go\nfunc (c ServerConfig) Transport() string\n```\nTransport returns the normalized transport (stdio | http | sse) for display/inspection.\n\n```go\ntype Tool struct {\n\tName        string         // namespaced for the model: mcp__\u003cserver\u003e__\u003craw\u003e\n\tServer      string         // declaring server name\n\tRaw         string         // original tool name on the server\n\tDescription string         // server-provided description\n\tInputSchema map[string]any // JSON-schema object, ready for a tool definition\n}\n```\nTool is one discovered MCP tool, flattened for memcode's tool registry.\n\n","path":"github.com/memcode-ai/memcode/internal/mcp","name":"mcp","synopsis":"Package mcp gives memcode an MCP (Model Context Protocol) client: it discovers the servers configured across scopes (local / project / user), connects to them (stdio, streamable HTTP, or SSE), lists their tools, and exposes a single Call entrypoint.","isRedistributable":true}
