Documentation
¶
Overview ¶
Package mcp implements the embedded MCP server that exposes the Escape CLI commands as MCP tools over HTTP.
Index ¶
- Constants
- Variables
- func BuildDocsQuery(query string) string
- func BuildStubTool(spec ToolSpec) (mcpgo.Tool, error)
- func BuiltinToolNames() []string
- func GuidanceTexts() ([]string, error)
- func InjectAuthContext(ctx context.Context, req *http.Request) context.Context
- func IsLoopbackHost(host string) bool
- func KnowledgeToolNames() []string
- func ListPageToolDescription(short string) string
- func NewIntentMiddleware(next http.Handler, opts IntentOptions) http.Handler
- func RegisterBuiltinTools(server *mcpserver.MCPServer, specs []ToolSpec)
- func RegisterCommandTools(server *mcpserver.MCPServer, specs []ToolSpec, options CommandExecutionOptions)
- func RegisterKnowledgeTools(server *mcpserver.MCPServer, opts KnowledgeOptions) error
- func RegisterPrompts(server *mcpserver.MCPServer)
- func RegisterPublicAPITools(server *mcpserver.MCPServer, opts PublicAPIOptions) error
- func RenderCurl(op indexedOperation, baseURL string) (string, string)
- func StemToken(value string) string
- type Auth
- type AuthMethod
- type ChatContext
- type ChatContextEntry
- type Classifier
- type CommandExecutionOptions
- type DocsSearchIndex
- type DocsSearchIndexOptions
- type ExecutionOptions
- type ExecutionResult
- type FlagBinding
- type IntentMode
- type IntentOptions
- type KnowledgeDocPage
- type KnowledgeOptions
- type KnowledgeSearchResult
- type LinkIntent
- type LinkTarget
- type OpenAPISearchIndex
- type OpenAPISearchIndexOptions
- type PlatformLink
- type PlatformLinkSelector
- type PlatformRoute
- type PublicAPIOptions
- type Server
- type ServerOptions
- type ToolDigest
- type ToolSpec
Constants ¶
const ConfirmProperty = "confirm"
ConfirmProperty is the MCP argument that authorizes a destructive tool call. Callers must set it to true only after a person has confirmed the action.
const ConfirmPropertyDescription = "Set to true only after the user explicitly confirmed this destructive action"
ConfirmPropertyDescription is the schema text shown for ConfirmProperty.
const DefaultListPageSize = 50
DefaultListPageSize is the page size injected when an MCP list tool is called without size or cursor. The CLI still fetches every page unless those flags are set.
const EmailsWaitTimeout = 25 * time.Second //nolint:mnd
EmailsWaitTimeout is the longest `emails wait` an MCP tool call will run. It stays below defaultToolExecutionTimeout so the CLI can return a pending result before the subprocess is killed.
const GetToolSpecToolName = "escape_get_tool_spec"
GetToolSpecToolName is the built-in tool that returns the full input schema of a compressed/stubbed tool on demand. Intent-aware tools/list serves minimal stubs for non-selected tools; the LLM uses this tool to zoom in when it decides to call one of them.
const ReasoningToolExecutionTimeout = 2 * time.Minute //nolint:mnd
ReasoningToolExecutionTimeout extends the default MCP subprocess budget for scans reasoning and scans coverage, which paginate large assessments.
const ServerInstructions = `` /* 1837-byte string literal not displayed */
ServerInstructions is returned by MCP initialize. External clients never see the in-app Copilot system prompt, so the rules that stop a partial configuration write from wiping a profile live here. Tool names match buildMCPToolName.
Variables ¶
ErrDocsIndexUnavailable is returned when the docs index can't be fetched.
var ErrDocsPageNotFound = errors.New("docs page not found")
ErrDocsPageNotFound is returned by GetPage when the docs index has no entry for the requested URL or path.
ErrOpenAPIUnavailable is returned when the OpenAPI spec cannot be fetched.
Functions ¶
func BuildDocsQuery ¶ added in v1.3.1
BuildDocsQuery drops noise words from a user query so the docs search index can match meaningful terms.
func BuildStubTool ¶ added in v1.3.1
BuildStubTool rebuilds a ToolSpec's mcp Tool with the heavy `body` property replaced by a small placeholder. Positional args and flag bindings are preserved verbatim because they are already compact and useful hints. The executor still uses the original spec (positional args, flags, body) at call time — this only affects what is advertised on tools/list.
`required` is reconstructed from the original RawInputSchema so any tool whose full schema marks `body` (or another non-positional flag) as required stays required in the stub. Otherwise compact_only mode would let the model emit calls that the executor immediately rejects.
func BuiltinToolNames ¶
func BuiltinToolNames() []string
BuiltinToolNames are the helper tools RegisterBuiltinTools adds beside the CLI catalog. Guidance may name these; it may not invent others.
func GuidanceTexts ¶
GuidanceTexts is the copy an MCP client shows the model: server instructions, each prompt description, each argument description, and every prompt rendered with sample arguments. A catalog test uses it to reject tool names that are not registered.
func InjectAuthContext ¶
InjectAuthContext derives a context that carries the credentials extracted from the incoming HTTP request so downstream tool handlers can access them.
Precedence: X-ESCAPE-API-KEY wins over Authorization when both are present, matching the pre-OAuth behavior. When the credential is extracted from a `Bearer` authorization header the raw header is NOT propagated: the backend API treats `Bearer <token>` as a JWT (verify), so leaking the header into ESCAPE_AUTHORIZATION would cause every downstream call to 401. See packages/cli/pkg/env/key.go GetAuthorizationHeader and services/api/src/lib/core/context/accessor.ts for the precedence that motivates this.
func IsLoopbackHost ¶ added in v1.3.5
IsLoopbackHost is a small helper exposed for tests.
func KnowledgeToolNames ¶
func KnowledgeToolNames() []string
KnowledgeToolNames are the documentation tools RegisterKnowledgeTools adds. Guidance may name these; it may not invent others.
func ListPageToolDescription ¶
ListPageToolDescription extends a command summary with the one-page contract agents need: the JSON shape, the default page size, and how to continue.
func NewIntentMiddleware ¶ added in v1.3.1
func NewIntentMiddleware(next http.Handler, opts IntentOptions) http.Handler
NewIntentMiddleware wraps next so that tools/list responses are rewritten according to Mode. All other requests pass through unchanged.
func RegisterBuiltinTools ¶
RegisterBuiltinTools registers the MCP-native helper tools (e.g. the tool discovery endpoint) that ship with the embedded server.
func RegisterCommandTools ¶
func RegisterCommandTools( server *mcpserver.MCPServer, specs []ToolSpec, options CommandExecutionOptions, )
RegisterCommandTools walks the supplied specs and registers one MCP handler per tool on the server. Each handler spawns a bounded CLI subprocess.
func RegisterKnowledgeTools ¶ added in v1.3.1
func RegisterKnowledgeTools(server *mcpserver.MCPServer, opts KnowledgeOptions) error
RegisterKnowledgeTools registers the knowledge_answer_question and knowledge_get_page tools on the given server.
func RegisterPrompts ¶
RegisterPrompts adds the workflow prompts external MCP clients can render. Each prompt is a short tool sequence. Names and arguments are part of the server contract.
func RegisterPublicAPITools ¶ added in v1.3.6
func RegisterPublicAPITools(server *mcpserver.MCPServer, opts PublicAPIOptions) error
RegisterPublicAPITools registers the public_api_answer_question tool on the given server.
func RenderCurl ¶ added in v1.3.6
RenderCurl produces a copy-paste-ready cURL command and, when the operation has query parameters the command does not send, a short list of those parameters (name, type, enum). The command includes required parameters and pagination parameters that declare a default. Other optional parameters are listed in the second result, not given a placeholder value. The output never contains the caller's real credentials — only `$ESCAPE_API_KEY`.
Types ¶
type Auth ¶
type Auth struct {
APIKey string
Authorization string
// Method records how the credential was delivered; used for telemetry.
Method AuthMethod
}
Auth carries the credentials extracted from an incoming MCP request, forwarded to the CLI subprocess through sanitized environment variables.
type AuthMethod ¶ added in v1.3.5
type AuthMethod string
AuthMethod identifies how the incoming request carried its credentials. Emitted as telemetry on every /mcp call so we can eventually retire the legacy paths (X-ESCAPE-API-KEY and `Key`) for the publicly-hosted MCP.
const ( // AuthMethodNone means the request carried no credentials. AuthMethodNone AuthMethod = "none" // AuthMethodAPIKeyHeader means the request used the legacy X-ESCAPE-API-KEY header. AuthMethodAPIKeyHeader AuthMethod = "x-escape-api-key" // AuthMethodAuthorizationKey means the request used `Authorization: Key <api-key>`. AuthMethodAuthorizationKey AuthMethod = "key" // AuthMethodAuthorizationBearer means the request used `Authorization: Bearer <api-key>`, // the OAuth 2.1 path. AuthMethodAuthorizationBearer AuthMethod = "bearer" )
type ChatContext ¶ added in v1.3.1
type ChatContext struct {
Current string `json:"current"`
PageContext string `json:"pageContext,omitempty"`
History []ChatContextEntry `json:"history,omitempty"`
}
ChatContext is the payload carried in the X-Escape-Chat-Context header. It holds the user's current message, optional page context (URL/title), and a few recent turns, so the classifier can resolve ambiguous pronouns and domain paraphrases (e.g. "findings" vs "issues", coverage page vs reasoning).
type ChatContextEntry ¶ added in v1.3.1
ChatContextEntry is one prior chat turn.
type Classifier ¶ added in v1.3.1
type Classifier interface {
Rank(ctx context.Context, chatCtx ChatContext, digest []ToolDigest) ([]string, error)
TopK() int
}
Classifier ranks tools by their relevance to a chat context. Nil Classifier means "not configured"; callers should treat that as "no ranking available" and fall back to a compact catalog.
func NewClassifierFromEnv ¶ added in v1.3.1
func NewClassifierFromEnv() (Classifier, error)
NewClassifierFromEnv builds a Classifier from the MCP_CLASSIFIER_* env vars. If the endpoint or api key are missing, returns (nil, nil) so callers can opt-in without hard-failing at boot.
type CommandExecutionOptions ¶
type CommandExecutionOptions struct {
PublicAPIURL string
}
CommandExecutionOptions carries the shared runtime inputs the tool handlers need that are not part of a specific tool spec.
type DocsSearchIndex ¶ added in v1.3.1
type DocsSearchIndex struct {
// contains filtered or unexported fields
}
DocsSearchIndex caches and queries the docs.escape.tech search index built by Docusaurus.
func NewDocsSearchIndex ¶ added in v1.3.1
func NewDocsSearchIndex(options DocsSearchIndexOptions) *DocsSearchIndex
NewDocsSearchIndex builds a docs search index with sensible defaults. Any option can be overridden by passing DocsSearchIndexOptions.
func (*DocsSearchIndex) GetPage ¶
func (d *DocsSearchIndex) GetPage(ctx context.Context, urlOrPath string) (*KnowledgeDocPage, error)
GetPage returns the full text of a documentation page identified by the URL or path surfaced in a Search result. Docusaurus indexes each section as its own location (page/#anchor), so the page body is rebuilt by concatenating every section whose location shares the target path, in index order. The text is plain (the search index strips markdown) and capped at maxDocsPageChars.
func (*DocsSearchIndex) Search ¶ added in v1.3.1
func (d *DocsSearchIndex) Search(ctx context.Context, queryInput string, limit int) ([]KnowledgeSearchResult, error)
Search returns the top N documentation matches for the given query.
type DocsSearchIndexOptions ¶ added in v1.3.1
type DocsSearchIndexOptions struct {
DocsSiteURL string
SearchIndexURL string
TTL time.Duration
HTTPClient *http.Client
}
DocsSearchIndexOptions configures the docs search index.
type ExecutionOptions ¶
type ExecutionOptions struct {
Command []string
DisplayCommand []string
Body any
Auth Auth
PublicAPIURL string
// Timeout is the budget the caller placed on ctx. The deadline error
// reports this duration. Zero means defaultToolExecutionTimeout.
Timeout time.Duration
}
ExecutionOptions carries the request-scoped inputs ExecuteCLICommand needs to spawn one CLI subprocess.
type ExecutionResult ¶
type ExecutionResult struct {
Stdout string
Stderr string
StdoutTruncated bool
StderrTruncated bool
ExitCode int
Payload any
}
ExecutionResult is the captured stdout/stderr/exit-code plus the parsed JSON payload (when the CLI produced valid JSON on stdout).
func ExecuteCLICommand ¶
func ExecuteCLICommand(ctx context.Context, options ExecutionOptions) (*ExecutionResult, error)
ExecuteCLICommand spawns the current escape-cli binary with the supplied command + arguments, forwards authentication through a sanitized environment, pipes the optional request body to stdin, and returns the structured result. The caller is responsible for binding a timeout on ctx. When that deadline is exceeded, the error names the budget and the get/list tool to poll. Models that only see "signal: killed" retry the same call.
type FlagBinding ¶
FlagBinding maps an MCP tool property to a CLI flag on the underlying Cobra command, including the type the value must be rendered as.
Default, when non-nil, is sent when the caller omits the property. A nil Default leaves the flag off the command line so the CLI's own default applies. buildMCPTool copies a JSON Schema default onto this field, so an omitted argument follows the schema (mcp-default) rather than the CLI flag.
Required means an omitted or empty value is refused before the subprocess starts. The CLI flag can stay optional. The catalog sets this when omitting the flag would widen the operation to every resource.
type IntentMode ¶ added in v1.3.1
type IntentMode string
IntentMode controls how the tools/list response is shaped. See the MCP_INTENT_FILTER env var for the runtime switch.
const ( // IntentModeOn runs the classifier when a chat-context header is present. // Selected tools ship with full schemas; the rest ship as compact stubs. IntentModeOn IntentMode = "on" // IntentModeCompactOnly always ships compact stubs for every command-backed // tool. The classifier is never consulted. Useful when the classifier is // misconfigured but we still need to fit under size limits. IntentModeCompactOnly IntentMode = "compact_only" // IntentModeOff disables the middleware and returns the raw library // response (every tool with its full schema). Emergency rollback only. IntentModeOff IntentMode = "off" )
func ModeFromEnv ¶ added in v1.3.1
func ModeFromEnv(fallback IntentMode) IntentMode
ModeFromEnv resolves MCP_INTENT_FILTER, defaulting to fallback when unset or invalid.
type IntentOptions ¶ added in v1.3.1
type IntentOptions struct {
Mode IntentMode
Classifier Classifier
Specs []ToolSpec
}
IntentOptions configures the HTTP interceptor.
type KnowledgeDocPage ¶
type KnowledgeDocPage struct {
Title string `json:"title"`
URL string `json:"url"`
Text string `json:"text"`
Truncated bool `json:"truncated"`
}
KnowledgeDocPage is the full page text returned by GetPage. Text is plain (the Docusaurus search index strips markdown) and capped at maxDocsPageChars; Truncated reports whether the cap was applied.
type KnowledgeOptions ¶ added in v1.3.1
type KnowledgeOptions struct {
DocsSiteURL string
DocsIndexURL string
PlatformBaseURL string
DocsTTL int64
}
KnowledgeOptions configures the answer_question tool. Zero-value fields fall back to the production defaults (docs.escape.tech, app.escape.tech).
type KnowledgeSearchResult ¶ added in v1.3.1
type KnowledgeSearchResult struct {
Title string `json:"title"`
URL string `json:"url"`
Snippet string `json:"snippet"`
}
KnowledgeSearchResult is what the tool returns per match.
type LinkIntent ¶ added in v1.3.1
type LinkIntent struct {
ExplicitLinkRequest bool
Target LinkTarget
}
LinkIntent is the detector's verdict.
func DetectLinkIntent ¶ added in v1.3.1
func DetectLinkIntent(query string) LinkIntent
DetectLinkIntent classifies a user question by the surface they want a link to (docs / platform / both / none) and whether they asked explicitly.
type LinkTarget ¶ added in v1.3.1
type LinkTarget string
LinkTarget describes which surfaces the link-intent detector thinks the question is about.
const ( LinkTargetDocs LinkTarget = "docs" LinkTargetPlatform LinkTarget = "platform" LinkTargetBoth LinkTarget = "both" LinkTargetNone LinkTarget = "none" )
LinkTarget* enumerate the surfaces the link-intent detector can route the caller to.
type OpenAPISearchIndex ¶ added in v1.3.6
type OpenAPISearchIndex struct {
// contains filtered or unexported fields
}
OpenAPISearchIndex caches and queries the public-API OpenAPI spec.
func NewOpenAPISearchIndex ¶ added in v1.3.6
func NewOpenAPISearchIndex(options OpenAPISearchIndexOptions) *OpenAPISearchIndex
NewOpenAPISearchIndex builds an OpenAPI search index with sensible defaults.
type OpenAPISearchIndexOptions ¶ added in v1.3.6
OpenAPISearchIndexOptions configures the OpenAPI-spec index.
type PlatformLink ¶ added in v1.3.1
PlatformLink is what the selector returns.
type PlatformLinkSelector ¶ added in v1.3.1
type PlatformLinkSelector struct {
// contains filtered or unexported fields
}
PlatformLinkSelector picks relevant platform deep links for a query.
func NewPlatformLinkSelector ¶ added in v1.3.1
func NewPlatformLinkSelector(baseURL string) (*PlatformLinkSelector, error)
NewPlatformLinkSelector builds a selector using the embedded catalog and the given base URL (e.g. https://app.escape.tech).
func NewPlatformLinkSelectorWithCatalog ¶ added in v1.3.1
func NewPlatformLinkSelectorWithCatalog(baseURL string, catalog []PlatformRoute) (*PlatformLinkSelector, error)
NewPlatformLinkSelectorWithCatalog lets callers override the catalog (mainly for tests). A nil/empty catalog falls back to the embedded one.
func (*PlatformLinkSelector) Select ¶ added in v1.3.1
func (s *PlatformLinkSelector) Select(queryContext string, limit int) []PlatformLink
Select returns up to `limit` platform links that match the query context. Ported from platform-links.ts (scoreRoute + createPlatformLinkSelector).
type PlatformRoute ¶ added in v1.3.1
PlatformRoute is a single entry of the curated platform-URL catalog generated from the SvelteKit (app) routes by services/frontend/scripts/generate-platform-routes.ts.
type PublicAPIOptions ¶ added in v1.3.6
PublicAPIOptions configures the public-API question tool. Zero values fall back to environment variables and then production defaults.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the embedded MCP server that exposes CLI commands over HTTP.
func NewServer ¶
func NewServer(options ServerOptions) *Server
NewServer builds a non-started embedded MCP server from the supplied options.
type ServerOptions ¶
type ServerOptions struct {
Version string
Port int
PublicAPIURL string
Tools []ToolSpec
// IntentMode controls the tools/list interceptor. When empty the server
// defaults to IntentModeCompactOnly, which serves compact stubs but never
// calls a classifier. Set to IntentModeOn to enable classifier-driven
// expansion (requires MCP_CLASSIFIER_* env vars). IntentModeOff disables
// the middleware entirely.
IntentMode IntentMode
// Classifier is an optional ranker used when IntentMode == IntentModeOn.
// If nil while IntentModeOn, the server behaves as IntentModeCompactOnly.
Classifier Classifier
// OAuth options. When IssuerURL and ResourceURL are both empty the
// server skips OAuth wiring and keeps the legacy X-ESCAPE-API-KEY
// behavior (useful for locally-run CLI MCP). In prod, both are set.
IssuerURL string
ResourceURL string
OAuthPrivateKeyPath string
}
ServerOptions configures the embedded HTTP-based MCP server.
type ToolDigest ¶ added in v1.3.1
ToolDigest is the compact tool metadata the classifier sees.
type ToolSpec ¶
type ToolSpec struct {
Name string
Path string
Description string
Tool mcpgo.Tool
Command []string
PositionalArgs []string
FlagBindings []FlagBinding
BodyProperty string
// AllowExtraArgs opts the tool into reading a free-form `args` string array
// from the request payload and forwarding it verbatim to the subprocess.
// Off by default so the Cobra-to-MCP mapping remains an explicit allowlist.
AllowExtraArgs bool
// ExecutionTimeout overrides defaultToolExecutionTimeout when set.
ExecutionTimeout time.Duration
// DefaultArgs are flag values used when the caller omitted them.
// List tools set size to DefaultListPageSize. That default is not applied
// when the caller already passed size or cursor: either one means they chose the page.
DefaultArgs map[string]any
// ForcedArgs are appended after caller arguments. Cobra keeps the last
// value of a repeated flag, so this is how the catalog caps emails wait
// under the tool budget no matter what the model sends.
ForcedArgs []string
// Destructive tools delete or bulk-mutate resources. The handler refuses
// the call unless the request sets ConfirmProperty to true. That property
// is MCP-only and is never forwarded as a CLI flag.
Destructive bool
}
ToolSpec fully describes one CLI-backed MCP tool: its MCP-level metadata plus the subprocess invocation plan (command path, positional + flag bindings, and optional stdin body property).