Documentation
¶
Index ¶
- Constants
- Variables
- func AddErrorContext(originalMessage, serverName, toolName string) string
- func ApplyDefaults(toolName string, args map[string]interface{}) map[string]interface{}
- func ContentItemType(item json.RawMessage) string
- func EnrichError(originalMessage string) string
- func FormatErrorWithHint(originalMessage, serverName, toolName string) string
- func GetAllParamDefaults(toolName string) map[string]interface{}
- func GetParamDefault(toolName, paramName string) interface{}
- func IsSupportedProtocolVersion(v string) bool
- func McpMethodNameAttr(method string) attribute.KeyValue
- func NegotiateProtocolVersion(requested string) string
- func ParseResourceURI(u string) (server, uri string, ok bool)
- func PromptName(server, name string) string
- func ProtocolAtLeast(v, minVersion string) bool
- func RecordCacheHit(ctx context.Context)
- func RecordCacheMiss(ctx context.Context)
- func RecordDedup(ctx context.Context, server string, n, savedTokens int64)
- func RecordDiscovery(_ context.Context, tokens int64)
- func RecordGovernedResult(ctx context.Context, server string, original, returned int64, truncated bool)
- func RecordInjectionDetection(ctx context.Context, action string)
- func RecordPolicyDecision(ctx context.Context, outcome, server string)
- func RecordProjection(ctx context.Context, server string, before, after int64)
- func RecordRateLimitWait(ctx context.Context)
- func RecordRedaction(ctx context.Context, n int64)
- func RecordSchemaListing(_ context.Context, nativeTokens, sentTokens int64)
- func RecordSummarization(ctx context.Context, server string, n, savedTokens, fallbacks int64)
- func RecordToolPinEvent(ctx context.Context, event, server string)
- func ResourceURI(server, uri string) string
- func ResponseRouteFrom(ctx context.Context) any
- func ResultURI(id string) string
- func SetTelemetryActive(active bool)
- func SplitToolName(ref string, servers []string) (server, tool string, err error)
- func UpstreamServerNameAttr(server string) attribute.KeyValue
- func ValidateParam(toolName, paramName string, value interface{}) (bool, string)
- func WithClientSession(ctx context.Context, s *ClientSession) context.Context
- func WithResponseRoute(ctx context.Context, route any) context.Context
- type AggregatedManifest
- type CallLog
- type CallRecord
- type CallToolResult
- type ClientCapabilities
- type ClientInfo
- type ClientSamplingCapability
- type ClientSession
- func (s *ClientSession) AcceptsRequests() bool
- func (s *ClientSession) AtLeast(minVersion string) bool
- func (s *ClientSession) Capabilities() json.RawMessage
- func (s *ClientSession) ClientInfo() ClientInfo
- func (s *ClientSession) DeliverResponse(id json.RawMessage, result json.RawMessage, rpcErr *Error) bool
- func (s *ClientSession) EnableContextRequests(fn ContextRequestFunc)
- func (s *ClientSession) EnableRequests(fn RequestFunc)
- func (s *ClientSession) ExposureMode() exposure.Mode
- func (s *ClientSession) HasCapability(name string) bool
- func (s *ClientSession) HasSubCapability(name, sub string) bool
- func (s *ClientSession) Initialized() bool
- func (s *ClientSession) PendingRequests() int
- func (s *ClientSession) ProtocolVersion() string
- func (s *ClientSession) Request(ctx context.Context, method string, params json.RawMessage) (json.RawMessage, *Error)
- type ContentBlock
- type ContextRequestFunc
- type Error
- type ErrorHint
- type FieldDescription
- type Firewall
- type Governor
- func (g *Governor) Close()
- func (g *Governor) DropSession(s *ClientSession)
- func (g *Governor) Enabled() bool
- func (g *Governor) Middleware() Middleware
- func (g *Governor) SetInjectionGuard(ig *InjectionGuard)
- func (g *Governor) SetServerNames(fn func() []string)
- func (g *Governor) Stats() GovernorStats
- func (g *Governor) Summary() string
- type GovernorStats
- type GovernorToolStats
- type Handler
- func (h *Handler) AttachUpstreamRelay(ctx context.Context)
- func (h *Handler) BeginUpstreamCall(ctx context.Context, server string, ...) (json.RawMessage, func())
- func (h *Handler) CachedTools() map[string][]Tool
- func (h *Handler) CallLogMiddleware(log *CallLog) Middleware
- func (h *Handler) ConfigureRelay(servers []*migrate.ServerConfig)
- func (h *Handler) ConfigureToolSearch(opts toolsearch.Options) *toolsearch.Index
- func (h *Handler) Exposure() *exposure.Resolver
- func (h *Handler) ExposureMiddleware() Middleware
- func (h *Handler) ExposureMode(ctx context.Context) exposure.Mode
- func (h *Handler) HandleRequest(ctx context.Context, req *Request) (*Response, error)
- func (h *Handler) HandleServerNotification(ctx context.Context, server, method string, params json.RawMessage)
- func (h *Handler) HandleServerRequest(ctx context.Context, server, method string, params json.RawMessage) (json.RawMessage, *errors.JSONRPCError)
- func (h *Handler) LoadPersistentToolCache()
- func (h *Handler) OnSessionClose(fn func(*ClientSession))
- func (h *Handler) OnToolsChanged(fn func(server string, tools []Tool))
- func (h *Handler) OpenSession(notify NotifyFunc) (*ClientSession, func())
- func (h *Handler) PopulateToolCache(ctx context.Context)
- func (h *Handler) RefreshServerTools(ctx context.Context, name string) error
- func (h *Handler) ResetManifest()
- func (h *Handler) SearchIndex() *toolsearch.Index
- func (h *Handler) ServerAdded(name string)
- func (h *Handler) ServerRemoved(name string)
- func (h *Handler) Sessions() []SessionInfo
- func (h *Handler) SetDefaultTimeout(timeout time.Duration)
- func (h *Handler) SetExposure(r *exposure.Resolver)
- func (h *Handler) SetGovernor(g *Governor)
- func (h *Handler) SetPolicy(p *Policy)
- func (h *Handler) SetRelayFirewall(fw *Firewall)
- func (h *Handler) SetRelayPolicy(server string, p RelayPolicy)
- func (h *Handler) SetTimeout(serverName string, timeout time.Duration)
- func (h *Handler) SetToolPins(g *ToolPins)
- func (h *Handler) SetToolRefreshRetryInterval(d time.Duration)
- func (h *Handler) StartBackgroundRefresh(ctx context.Context)
- func (h *Handler) ToolCount(server string) (int, bool)
- func (h *Handler) ToolRefreshStatus(server string) ToolRefreshStatus
- func (h *Handler) Use(mws ...Middleware)
- type HealthcheckCapability
- type Icon
- type InitializeParams
- type InitializeResult
- type InjectionGuard
- func (g *InjectionGuard) Check(req *Request) *Response
- func (g *InjectionGuard) CheckContext(ctx context.Context, req *Request) *Response
- func (g *InjectionGuard) CheckResponse(ctx context.Context, req *Request, resp *Response) *Response
- func (g *InjectionGuard) CheckServerRequest(ctx context.Context, server, method string, params json.RawMessage) (json.RawMessage, *Error)
- func (g *InjectionGuard) Configure(cfg *injection.Config)
- func (g *InjectionGuard) Enabled() bool
- func (g *InjectionGuard) Middleware() Middleware
- func (g *InjectionGuard) PolicyCount() int
- func (g *InjectionGuard) ScansResponses() bool
- func (g *InjectionGuard) Set(c *injection.Classifier, d *injection.Dispatcher)
- func (g *InjectionGuard) SetOptions(o InjectionGuardOptions)
- type InjectionGuardOptions
- type Middleware
- type Next
- type NotifyFunc
- type ParamInfo
- type ParameterMeta
- type Policy
- type Prompt
- type PromptArgument
- type PromptsCapability
- type PromptsListParams
- type PromptsListResult
- type Redaction
- func (r *Redaction) Configure(cfg *bouncer.Config)
- func (r *Redaction) Enabled() bool
- func (r *Redaction) PatternCount() int
- func (r *Redaction) RedactRequest(req *Request) error
- func (r *Redaction) RedactRequestContext(ctx context.Context, req *Request) error
- func (r *Redaction) RedactResponse(resp *Response) error
- func (r *Redaction) RedactResponseContext(ctx context.Context, resp *Response) error
- func (r *Redaction) RedactText(s string) string
- func (r *Redaction) Redactor() *bouncer.Redactor
- func (r *Redaction) RequestMiddleware() Middleware
- func (r *Redaction) ResponseMiddleware() Middleware
- func (r *Redaction) SetRedactor(red *bouncer.Redactor)
- type RelayPolicy
- type Request
- type RequestFunc
- type Resource
- type ResourcesCapability
- type ResourcesListParams
- type ResourcesListResult
- type Response
- type ResponseCache
- type ReturnSchema
- type Root
- type RootsCapability
- type ServerCapabilities
- type ServerInfo
- type ServerSamplingCapability
- type SessionInfo
- type StructuredTool
- type TelemetryCounters
- type Tool
- type ToolAnnotations
- type ToolCache
- type ToolDefinition
- type ToolExample
- type ToolPins
- type ToolRefreshStatus
- type ToolsCallParams
- type ToolsCallResult
- type ToolsCapability
- type ToolsListParams
- type ToolsListResult
Constants ¶
const ( // ResourceURIScheme is the scheme of namespaced resource URIs. ResourceURIScheme = "leanproxy" // ErrCodeResourceNotFound is the MCP error code for an unknown resource. ErrCodeResourceNotFound = -32002 )
const ( CallOK = "ok" CallError = "error" // a JSON-RPC or transport error CallToolError = "tool_error" // a result with isError: true )
Call statuses.
const ( ProtocolVersion20241105 = "2024-11-05" ProtocolVersion20250326 = "2025-03-26" ProtocolVersion20250618 = "2025-06-18" ProtocolVersion20251125 = "2025-11-25" // LatestProtocolVersion is the newest revision LeanProxy supports. It // is what a client asking for an unknown revision is offered, and what // the pool requests from upstream servers (pool.RequestedProtocolVersion // must stay equal to it; a test enforces that). LatestProtocolVersion = ProtocolVersion20251125 )
MCP protocol revisions LeanProxy speaks (issue #307).
const ( NotificationResourcesListChanged = "notifications/resources/list_changed" NotificationPromptsListChanged = "notifications/prompts/list_changed" NotificationResourcesUpdated = "notifications/resources/updated" NotificationProgress = "notifications/progress" NotificationCancelled = "notifications/cancelled" //nolint:misspell // MCP protocol method name NotificationRootsListChanged = "notifications/roots/list_changed" NotificationElicitationComplete = "notifications/elicitation/complete" )
Server-to-client notifications LeanProxy emits.
const ( MethodInitialize = "initialize" MethodInitialized = "notifications/initialized" MethodToolsList = "tools/list" MethodToolsCall = "tools/call" MethodResourcesList = "resources/list" MethodResourcesTemplatesList = "resources/templates/list" MethodResourcesRead = "resources/read" MethodResourcesSubscribe = "resources/subscribe" MethodResourcesUnsubscribe = "resources/unsubscribe" MethodPromptsList = "prompts/list" MethodPromptsGet = "prompts/get" MethodPing = "ping" MethodShutdown = "shutdown" )
const ( ContentTypeText = "text" ContentTypeImage = "image" ContentTypeAudio = "audio" ContentTypeResource = "resource" ContentTypeResourceLink = "resource_link" )
Content item types of MCP tool results and prompt messages.
const ( ErrCodeParseError = -32700 ErrCodeInvalidRequest = -32600 ErrCodeMethodNotFound = -32601 ErrCodeInvalidParams = -32602 ErrCodeInternalError = -32603 ErrCodeServerError = -32000 )
const ( // ClientRequestTimeout bounds how long a relayed request waits for the // client's answer when the upstream never cancels it. Elicitation waits // for a human, hence the generous bound. ClientRequestTimeout = 10 * time.Minute )
const DefaultCallLogSize = 500
DefaultCallLogSize is how many tool calls the call log keeps.
const DefaultToolRefreshRetryInterval = 30 * time.Second
DefaultToolRefreshRetryInterval is how often the background refresh retries servers whose tool list is unknown or whose last refresh failed. A server that keeps failing is retried less and less often, see MaxToolRefreshRetryInterval.
const ErrCodeRequestTimeout = -32001
ErrCodeRequestTimeout is the error an upstream gets when the client did not answer a relayed request within ClientRequestTimeout.
const InjectionRedacted = "[CONTENT_REDACTED]"
InjectionRedacted replaces each span of text the redact action removes.
const JSONRPCVersion = "2.0"
const MaxToolRefreshRetryInterval = 10 * time.Minute
MaxToolRefreshRetryInterval caps the per-server backoff of the periodic retry: the delay doubles after every failure (30s, 1m, 2m, ...) up to this. A server that needs an authorization nobody gives it would otherwise be asked, and its failure logged, every 30 seconds forever.
const NotificationToolsListChanged = "notifications/tools/list_changed"
NotificationToolsListChanged tells a client to fetch tools/list again.
const ReadResultToolName = "read_result"
ReadResultToolName is the gateway tool that serves spilled results.
const RedactionFailedMessage = "Secret redaction failed; request not forwarded"
RedactionFailedMessage is returned to the client when a request's params could not be safely redacted. The request is never forwarded in that case.
const ResponseRedactionFailedMessage = "Secret redaction failed; response withheld"
ResponseRedactionFailedMessage replaces a response that could not be safely redacted. The original response is never written to the client.
const ResultURIPrefix = resourceURIPrefix + "results/"
ResultURIPrefix starts the resource URI of a spilled result: leanproxy://results/<result_id>.
Variables ¶
var ErrorHintRegistry = map[string][]ErrorHint{
"repository": {
{
Original: "Could not resolve to a Repository",
Suggestion: "Check the owner/repo spelling. Ensure the repository exists and you have access. Tip: Use the exact format 'owner/repo' (e.g., 'mmornati/leanproxy-mcp').",
Action: "check_repo",
Reference: "https://docs.github.com/en/github/finding-open-source-projects-on-github",
},
},
"not running": {
{
Original: "is not running",
Suggestion: "The MCP server is not running. Run 'leanproxy server start <server_name>' or check server status with 'leanproxy status'.",
Action: "restart_server",
},
},
"not healthy": {
{
Original: "not healthy",
Suggestion: "The server is in an error state. Check 'leanproxy-mcp status --running' for details. The server will automatically restart on the next request.",
Action: "restart_server",
},
},
"server not available": {
{
Original: "server not available",
Suggestion: "The server crashed or failed to start. Check the logs at /tmp/leanproxy.log for error details. The server will attempt to restart automatically.",
Action: "check_logs",
},
},
"signal: killed": {
{
Original: "signal: killed",
Suggestion: "The server process was killed (likely by the system or OOM). Check /tmp/leanproxy.log for more details. Auto-restart will attempt recovery.",
Action: "check_logs",
},
},
"command not found": {
{
Original: "command not found",
Suggestion: "The server command (e.g., npx, uv) is not installed or not in PATH. Check your configuration and install the required dependencies.",
Action: "check_dependencies",
},
},
"failed": {
{
Original: "server error",
Suggestion: "The remote server encountered an error. Try again in a few moments, or check the server logs for more details.",
Action: "retry",
},
},
"not authenticated": {
{
Original: "not authenticated",
Suggestion: "Authentication required. Check your credentials configuration for this server.",
Action: "check_auth",
},
{
Original: "401",
Suggestion: "Authentication failed. Verify your API token or credentials are correct.",
Action: "check_auth",
},
},
"forbidden": {
{
Original: "403",
Suggestion: "Access denied. You may not have permission for this operation. Check your API token scopes.",
Action: "check_permissions",
},
{
Original: "permission denied",
Suggestion: "Insufficient permissions. Verify your account has the required access rights.",
Action: "check_permissions",
},
},
"not found": {
{
Original: "404",
Suggestion: "The requested resource was not found. Check if the resource exists and the URL is correct.",
Action: "verify_resource",
},
},
"rate limited": {
{
Original: "429",
Suggestion: "Rate limit exceeded. Wait a moment before retrying, or check if you need to configure rate limiting.",
Action: "wait_retry",
},
{
Original: "rate limit",
Suggestion: "Too many requests. Consider adding a delay between requests or reducing request frequency.",
Action: "wait_retry",
},
},
"timeout": {
{
Original: "timeout",
Suggestion: "The request timed out. The server may be slow or unavailable. Try again or increase timeout settings.",
Action: "retry",
},
{
Original: "context deadline exceeded",
Suggestion: "The request took too long. Try again or check if the server is experiencing issues.",
Action: "retry",
},
},
"invalid params": {
{
Original: "invalid params",
Suggestion: "Check the parameter names and types. Use list_servers to get servers, then list_tools to see available parameters.",
Action: "check_params",
},
{
Original: "missing",
Suggestion: "A required parameter is missing. Use list_servers to get servers, then list_tools to see required parameters.",
Action: "check_params",
},
},
"connection refused": {
{
Original: "connection refused",
Suggestion: "Cannot connect to the server. Verify the server is running and the connection settings are correct.",
Action: "check_server",
},
},
"tool not found": {
{
Original: "tool not found",
Suggestion: "The tool doesn't exist on this server. Use search_tools to find the right tool, or list_tools to browse a server.",
Action: "search_tools",
},
},
}
var InvokeToolParamDefaults = map[string]interface{}{}
var InvokeToolParamMeta = map[string]ParameterMeta{ "server": { Required: true, Description: "Server name from search_tools or list_servers (e.g., 'github', 'garmin', 'filesystem'). Must be a configured and running MCP server.", }, "tool": { Required: true, Description: "Tool name from search_tools or list_tools (e.g., 'list_issues', 'get_activities'). Do NOT prefix with server name.", }, "arguments": { Required: false, Description: "Tool arguments as key-value pairs. Refer to list_tools output for available parameters. Pass empty object {} if no arguments needed.", }, }
var LeanproxyTools = []ToolDefinition{ { Name: "search_tools", ReadOnly: true, Description: "Find the best tools for a task across all servers. Returns the top matches with their input schema; call them with invoke_tool.", Categories: []string{"discovery", "meta"}, Returns: ReturnSchema{ Type: "object", Description: "Returns a content block with one line per matching tool, best first", Fields: []FieldDescription{ {Name: "content", Type: "array", Desc: "Array of text content blocks"}, }, }, InputSchema: json.RawMessage(`{ "type": "object", "properties": { "query": {"type": "string"}, "k": {"type": "integer", "default": 5, "maximum": 20}, "server": {"type": "string", "description": "optional filter"} }, "required": ["query"] }`), }, { Name: "list_servers", ReadOnly: true, Description: "List configured MCP servers: transport, state, tool count.", Categories: []string{"discovery", "meta"}, Returns: ReturnSchema{ Type: "object", Description: "Returns a content block with one line per server", Fields: []FieldDescription{ {Name: "content", Type: "array", Desc: "Array of text content blocks"}, }, }, InputSchema: json.RawMessage(`{ "type": "object", "properties": {} }`), }, { Name: "list_tools", ReadOnly: true, Description: "Browse all tools of one server. Prefer search_tools.", Categories: []string{"discovery", "meta"}, Returns: ReturnSchema{ Type: "object", Description: "Returns a content block with formatted tool list for the specified server", Fields: []FieldDescription{ {Name: "content", Type: "array", Desc: "Array of text content blocks"}, }, }, InputSchema: json.RawMessage(`{ "type": "object", "properties": { "server_name": { "type": "string", "description": "From list_servers." }, "max_description_chars": { "type": "number", "description": "Max desc length (default 200)", "default": 200 } }, "required": ["server_name"] }`), }, { Name: "invoke_tool", Description: "Invoke a tool found by search_tools.", Categories: []string{"execution", "meta"}, Returns: ReturnSchema{ Type: "object", Description: "Returns the result from the remote MCP tool invocation", Fields: []FieldDescription{ {Name: "content", Type: "array", Desc: "Array of content blocks from tool"}, }, }, InputSchema: json.RawMessage(`{ "type": "object", "properties": { "server": { "type": "string", "description": "Server of the tool." }, "tool": { "type": "string", "description": "Tool name, no server prefix." }, "arguments": { "type": "object", "description": "Tool arguments." } }, "required": ["server", "tool"], "additionalProperties": false }`), }, }
LeanproxyTools are the gateway tools the proxy exposes in tools/list. The recommended flow is search_tools -> invoke_tool; list_servers and list_tools stay for browsing.
var ListToolsParamDefaults = map[string]interface{}{
"max_description_chars": 200,
}
var ListToolsParamMeta = map[string]ParameterMeta{ "server_name": { Required: true, Default: nil, Description: "MCP server name (from list_servers). Required - identifies which server's tools to list.", SuggestedValues: []string{"github", "garmin", "filesystem", "intervals"}, }, "max_description_chars": { Required: false, Default: 200, Min: 50, Max: 500, Description: "Maximum characters for tool descriptions. Default: 200. Range: 50-500.", }, }
var SupportedProtocolVersions = []string{ ProtocolVersion20251125, ProtocolVersion20250618, ProtocolVersion20250326, ProtocolVersion20241105, }
SupportedProtocolVersions lists every MCP revision the front ends negotiate, newest first. It is the single source of truth for version negotiation.
Functions ¶
func AddErrorContext ¶ added in v0.5.2
func ApplyDefaults ¶ added in v0.5.2
func ContentItemType ¶ added in v1.1.1
func ContentItemType(item json.RawMessage) string
ContentItemType returns the "type" of one raw content item, or "" when it has none.
func EnrichError ¶ added in v0.5.2
func FormatErrorWithHint ¶ added in v0.5.2
func GetAllParamDefaults ¶ added in v0.5.2
func GetParamDefault ¶ added in v0.5.2
func GetParamDefault(toolName, paramName string) interface{}
func IsSupportedProtocolVersion ¶ added in v1.1.1
IsSupportedProtocolVersion reports whether v is one of SupportedProtocolVersions.
func McpMethodNameAttr ¶ added in v1.1.1
McpMethodNameAttr returns the semconv `mcp.method.name` attribute. It is exported so other packages (e.g. serve's own dispatch loop) that build spans outside the pkg/mcp pipeline can reuse the same key.
func NegotiateProtocolVersion ¶ added in v1.1.1
NegotiateProtocolVersion implements the MCP version negotiation rule: the server answers with the version the client requested when it supports it, and otherwise with the latest version it supports (the client then decides whether to continue).
func ParseResourceURI ¶ added in v1.1.1
ParseResourceURI splits a namespaced resource URI into its server and the upstream URI. ok is false when u is not a leanproxy:// URI.
func PromptName ¶ added in v1.1.1
PromptName returns the namespaced name of an upstream prompt.
func ProtocolAtLeast ¶ added in v1.1.1
ProtocolAtLeast reports whether revision v is min or newer. Revisions are ISO dates, so they compare as strings. An empty v (a client that never initialized) counts as the oldest revision.
func RecordCacheHit ¶ added in v1.1.1
RecordCacheHit / RecordCacheMiss increment the response-cache counters.
func RecordCacheMiss ¶ added in v1.1.1
func RecordDedup ¶ added in v1.1.1
RecordDedup records n results the response governor replaced with an in-session dedup marker (#321), and the estimated tokens it saved. Only counts and the server name are recorded, never a result or its hash.
func RecordDiscovery ¶ added in v1.1.1
RecordDiscovery records one discovery-tool result (search_tools, list_tools, list_servers) and its estimated tokens. Only a count and a token size, never the result text.
func RecordGovernedResult ¶ added in v1.1.1
func RecordGovernedResult(ctx context.Context, server string, original, returned int64, truncated bool)
RecordGovernedResult records one tool result the response governor (#319) saw: its estimated tokens before and after, and whether it was shortened. Only token counts and the server name are recorded, never the result.
func RecordInjectionDetection ¶ added in v1.1.1
RecordInjectionDetection increments the injection-detection counter for action (e.g. "block", "quarantine", "redact", "annotate", "log").
func RecordPolicyDecision ¶ added in v1.1.1
RecordPolicyDecision increments the policy-decision counter (#314) for outcome (e.g. "allow", "deny", "confirm_approved") and the upstream server. Only the outcome and the server name are recorded, never the tool's arguments.
func RecordProjection ¶ added in v1.1.1
RecordProjection records one tool result the response governor projected (#320): the estimated tokens of its projected parts before and after. Only token counts and the server name are recorded, never the result.
func RecordRateLimitWait ¶ added in v1.1.1
RecordRateLimitWait increments the rate-limit-wait counter.
func RecordRedaction ¶ added in v1.1.1
RecordRedaction increments the redaction counter (OTel + the plain snapshot). Called by the redaction middleware for every pattern match.
func RecordSchemaListing ¶ added in v1.1.1
RecordSchemaListing records one tools/list response sent to a client (issue #324): its estimated tokens with (native) and without (sent) the router's compaction. Only counts, never a tool name or schema. The ctx parameter is unused today (no dedicated OTel instrument yet) but kept for symmetry with the other Record* helpers and so one can be added without changing every call site.
func RecordSummarization ¶ added in v1.1.1
RecordSummarization records n results the response governor replaced with a local-LLM summary (#321), the estimated tokens it saved, and fallbacks results that fell back to truncation instead. Only counts and the server name are recorded, never a result or a summary.
func RecordToolPinEvent ¶ added in v1.1.1
RecordToolPinEvent counts a tool pinning event (#310) by kind and upstream server. Only the event kind and the server name are recorded, never a tool definition.
func ResourceURI ¶ added in v1.1.1
ResourceURI returns the namespaced form of an upstream resource URI (or URI template).
func ResponseRouteFrom ¶ added in v1.1.1
ResponseRouteFrom returns the route carried by ctx, or nil.
func SetTelemetryActive ¶ added in v1.1.1
func SetTelemetryActive(active bool)
SetTelemetryActive is called once at startup (see cmd/telemetry.go) once pkg/telemetry.Resolve has decided whether OTLP exporting is actually enabled. It must be set before the first request reaches the pipeline.
func SplitToolName ¶ added in v1.1.1
SplitToolName splits a namespaced tool reference such as "server_tool" or "server.tool" into its server and tool parts. Unlike a naive split on the first separator, it matches the longest name in servers that is a prefix of ref immediately followed by '.' or '_', so a server literally named "my_srv" is reachable via "my_srv_tool" and overlapping names (e.g. "git" and "github") resolve to the correct owner instead of the first partial match.
It returns an error when no configured server name is a matching prefix of ref.
func UpstreamServerNameAttr ¶ added in v1.1.1
UpstreamServerNameAttr and UpstreamSpanName are shared with the CLIENT span the handler starts around the upstream call (see sendUpstream in handlers.go), kept here so the attribute key stays in one place.
func ValidateParam ¶ added in v0.5.2
func WithClientSession ¶ added in v1.1.1
func WithClientSession(ctx context.Context, s *ClientSession) context.Context
WithClientSession returns a context carrying s: requests handled with it read and update that session.
func WithResponseRoute ¶ added in v1.1.1
WithResponseRoute returns a context carrying route, an opaque value a front end attaches to a client request so that the server-to-client messages it causes go back where that request is answered (the Streamable HTTP front end, #309, uses the request's response stream). The relay keeps the route of every upstream call, so a request an upstream sends during a call carries the route of that call.
Types ¶
type AggregatedManifest ¶
type CallLog ¶ added in v1.1.1
type CallLog struct {
// contains filtered or unexported fields
}
CallLog is a fixed-size ring of the most recent tool calls, for the admin views. It is in memory only and safe for concurrent use.
func NewCallLog ¶ added in v1.1.1
NewCallLog returns a log keeping the last size calls (DefaultCallLogSize when size is not positive).
type CallRecord ¶ added in v1.1.1
type CallRecord struct {
Time time.Time `json:"time"`
SessionID string `json:"session_id,omitempty"`
Client string `json:"client,omitempty"`
Server string `json:"server"`
Tool string `json:"tool"`
DurationMs float64 `json:"duration_ms"`
Status string `json:"status"`
// Error is the (redacted, truncated) error message of a failed call.
Error string `json:"error,omitempty"`
ResponseBytes int `json:"response_bytes"`
}
CallRecord is one tool call as the proxy saw it. It never holds the call's arguments or its result: only who called what, how long it took and how it ended.
type CallToolResult ¶ added in v1.1.1
type CallToolResult struct {
Content []json.RawMessage `json:"content"`
// StructuredContent is the tool's structured output (2025-06-18).
StructuredContent json.RawMessage `json:"structuredContent,omitempty"`
IsError bool `json:"isError,omitempty"`
Meta json.RawMessage `json:"_meta,omitempty"`
}
CallToolResult is a tools/call result as an upstream server returns it. Content items are kept raw (every item type — text, image, audio, resource, resource_link, and any future one — survives unchanged); ContentItemType tells them apart.
type ClientCapabilities ¶
type ClientCapabilities struct {
Roots *RootsCapability `json:"roots,omitempty"`
Sampling *ClientSamplingCapability `json:"sampling,omitempty"`
}
type ClientInfo ¶
type ClientSamplingCapability ¶
type ClientSamplingCapability struct{}
type ClientSession ¶ added in v1.1.1
type ClientSession struct {
// contains filtered or unexported fields
}
ClientSession is the MCP session state of one connected client: the protocol revision negotiated by its initialize request, what it declared about itself, and how to send it notifications. `server run --stdio` has one session for its lifetime; `serve` opens one per TCP connection.
func ClientSessionFrom ¶ added in v1.1.1
func ClientSessionFrom(ctx context.Context) *ClientSession
ClientSessionFrom returns the session carried by ctx, or nil.
func (*ClientSession) AcceptsRequests ¶ added in v1.1.1
func (s *ClientSession) AcceptsRequests() bool
AcceptsRequests reports whether the front end can deliver server-to-client requests to this client.
func (*ClientSession) AtLeast ¶ added in v1.1.1
func (s *ClientSession) AtLeast(minVersion string) bool
AtLeast reports whether the session negotiated revision minVersion or newer.
func (*ClientSession) Capabilities ¶ added in v1.1.1
func (s *ClientSession) Capabilities() json.RawMessage
Capabilities returns the client capabilities declared in initialize, as sent.
func (*ClientSession) ClientInfo ¶ added in v1.1.1
func (s *ClientSession) ClientInfo() ClientInfo
ClientInfo returns what the client said about itself in initialize.
func (*ClientSession) DeliverResponse ¶ added in v1.1.1
func (s *ClientSession) DeliverResponse(id json.RawMessage, result json.RawMessage, rpcErr *Error) bool
DeliverResponse hands the client's answer to a server-to-client request to its waiter. It reports whether id named a pending request; an answer to an unknown (already canceled or never sent) request is dropped.
func (*ClientSession) EnableContextRequests ¶ added in v1.1.1
func (s *ClientSession) EnableContextRequests(fn ContextRequestFunc)
EnableContextRequests is EnableRequests for a front end that routes each request by its context (see ContextRequestFunc).
func (*ClientSession) EnableRequests ¶ added in v1.1.1
func (s *ClientSession) EnableRequests(fn RequestFunc)
EnableRequests lets the relay send server-to-client requests to this client through fn. A front end that cannot carry them never calls it, and the session then never gets any (the upstream is answered -32601).
func (*ClientSession) ExposureMode ¶ added in v1.1.1
func (s *ClientSession) ExposureMode() exposure.Mode
ExposureMode returns the exposure mode decided at initialize ("" before that).
func (*ClientSession) HasCapability ¶ added in v1.1.1
func (s *ClientSession) HasCapability(name string) bool
HasCapability reports whether the client declared the named capability (e.g. "sampling", "elicitation", "roots") in its initialize request.
func (*ClientSession) HasSubCapability ¶ added in v1.1.1
func (s *ClientSession) HasSubCapability(name, sub string) bool
HasSubCapability reports whether the client declared capability name with the member sub (e.g. elicitation.url).
func (*ClientSession) Initialized ¶ added in v1.1.1
func (s *ClientSession) Initialized() bool
Initialized reports whether the client completed initialize.
func (*ClientSession) PendingRequests ¶ added in v1.1.1
func (s *ClientSession) PendingRequests() int
PendingRequests returns the number of server-to-client requests waiting for the client.
func (*ClientSession) ProtocolVersion ¶ added in v1.1.1
func (s *ClientSession) ProtocolVersion() string
ProtocolVersion returns the negotiated revision, or "" before initialize.
func (*ClientSession) Request ¶ added in v1.1.1
func (s *ClientSession) Request(ctx context.Context, method string, params json.RawMessage) (json.RawMessage, *Error)
Request sends a server-to-client request to the client and waits for its answer. When ctx ends first (the upstream canceled, or its connection died) the pending entry is freed and the client gets the MCP cancel notification for the request. The returned error is what the upstream should be answered.
type ContentBlock ¶
type ContextRequestFunc ¶ added in v1.1.1
ContextRequestFunc is a RequestFunc that also gets the context of the relayed request. A front end with several response streams per session (Streamable HTTP, #309) reads from it, with ResponseRouteFrom, the stream of the client request the message belongs to.
type Error ¶
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
Data json.RawMessage `json:"data,omitempty"`
}
type ErrorHint ¶ added in v0.5.2
func GetAllHintsForError ¶ added in v0.5.2
func GetErrorHint ¶ added in v0.5.2
type FieldDescription ¶ added in v0.5.2
type Firewall ¶ added in v1.1.1
type Firewall struct {
Redaction *Redaction
Injection *InjectionGuard
}
Firewall is the "Token Firewall": the security middlewares every front end (`server run --stdio` and `serve`) installs, built from one config.
func NewFirewall ¶ added in v1.1.1
NewFirewall builds the firewall from the `bouncer:` and `injection:` config blocks. Redaction is on by default (built-in patterns when bouncerCfg is nil); injection classification runs only when an `injection:` block enables it.
func (*Firewall) Middlewares ¶ added in v1.1.1
func (f *Firewall) Middlewares() []Middleware
Middlewares returns the firewall stages in pipeline order, outermost first:
client → RedactResponse( RedactRequest → Injection( next ) ) → client
The injection stage classifies the (already redacted) request before next and the response next returns before it is redacted and written; a warning or block notice it adds therefore also passes the response redactor.
The response redactor is outermost so it also covers responses produced by the other stages (e.g. a quarantine notice) and by any middleware added after the firewall. Request redaction runs before the injection classifier so a quarantined payload never lands on disk with a secret in it.
type Governor ¶ added in v1.1.1
type Governor struct {
// contains filtered or unexported fields
}
Response token governor, part 1 (issue #319): smart truncation of large tool results and spill-to-resource with paged retrieval.
Pipeline placement ¶
The governor sits right inside the telemetry span, OUTSIDE tool pinning, the per-tool policy, the response cache and the Token Firewall:
telemetry → governor → tool_pinning → policy → cache → redact_response → redact_request → injection → dispatch
so that:
- it only ever sees responses that were redacted (redact_response) and scanned for prompt injection (injection) already: what it spills and serves back through read_result is exactly what the client would have received in full;
- the response cache stores the full (redacted) response and every answer, hit or miss, is governed the same way for the session that asked. A cached, governed answer can therefore never carry a result_id of another session;
- read_result and resources/read of leanproxy://results/<id> are answered from the spill store before any other stage: they only return data that already went through all of them.
Field projection (#320) runs on the same parsed result, before the budget is applied (see shortenResult): it too only sees redacted, scanned content, and whatever it leaves out stays retrievable in full through read_result. In-session dedup (#321) can reuse the spill store and read_result the same way.
func NewGovernor ¶ added in v1.1.1
NewGovernor builds the governor from the `response:` block. A nil cfg or one with enabled: false gives a disabled governor whose Middleware only calls next. A disk spill store that cannot be created falls back to memory (with a warning).
func (*Governor) Close ¶ added in v1.1.1
func (g *Governor) Close()
Close stops the janitor, removes every spilled result (and, with spill.disk, the per-process directory) and closes the summarizer client. Called on shutdown.
func (*Governor) DropSession ¶ added in v1.1.1
func (g *Governor) DropSession(s *ClientSession)
DropSession removes every result spilled for s, and its dedup index (#321): a session's dedup memory never outlives the session.
func (*Governor) Middleware ¶ added in v1.1.1
func (g *Governor) Middleware() Middleware
Middleware returns the governor stage. See the Governor doc comment for where it must sit in the pipeline.
func (*Governor) SetInjectionGuard ¶ added in v1.1.1
func (g *Governor) SetInjectionGuard(ig *InjectionGuard)
SetInjectionGuard wires the guard summarized output (#321) is scanned with, the same as any other tool output (checkResponse). Without it, a summary is used unscanned; cmd wires this after building the firewall.
func (*Governor) SetServerNames ¶ added in v1.1.1
SetServerNames tells the governor which servers exist, to split namespaced tool names. Without it the handler's servers are used.
func (*Governor) Stats ¶ added in v1.1.1
func (g *Governor) Stats() GovernorStats
Stats returns a snapshot of the accounting.
type GovernorStats ¶ added in v1.1.1
type GovernorStats struct {
Enabled bool `json:"enabled"`
MaxTokens int `json:"max_tokens"`
Results int64 `json:"results"`
Truncated int64 `json:"truncated"`
Spilled int64 `json:"spilled"`
ReadResult int64 `json:"read_result_calls"`
OriginalTokens int64 `json:"original_tokens"`
ReturnedTokens int64 `json:"returned_tokens"`
SavedTokens int64 `json:"saved_tokens"`
// Field projection (#320): results projected and the estimated
// tokens it removed (part of SavedTokens).
Projected int64 `json:"projected"`
ProjectionSavedTokens int64 `json:"projection_saved_tokens"`
ProjectionRules int `json:"projection_rules"`
DefaultProjections bool `json:"default_projections"`
// In-session dedup (#321): results replaced by a dedup marker
// (never across sessions) and the estimated tokens it saved (part of
// SavedTokens).
DedupEnabled bool `json:"dedup_enabled"`
DedupHits int64 `json:"dedup_hits"`
DedupSavedTokens int64 `json:"dedup_saved_tokens"`
// Summarization (#321): results replaced by a local-LLM summary, the
// estimated tokens it saved (part of SavedTokens), and how many
// summarization attempts fell back to truncation.
SummarizeEnabled bool `json:"summarize_enabled"`
Summarized int64 `json:"summarized"`
SummarizeSavedTokens int64 `json:"summarize_saved_tokens"`
SummarizeFallbacks int64 `json:"summarize_fallbacks"`
Store governor.StoreStats `json:"store"`
ByTool []GovernorToolStats `json:"by_tool,omitempty"`
}
GovernorStats is the governor's accounting, as exposed on /metrics. Only numbers: never a payload.
type GovernorToolStats ¶ added in v1.1.1
type GovernorToolStats struct {
Tool string `json:"tool"`
Results int64 `json:"results"`
Truncated int64 `json:"truncated"`
OriginalTokens int64 `json:"original_tokens"`
ReturnedTokens int64 `json:"returned_tokens"`
// Field projection (#320): results projected, and the estimated
// tokens the projection removed (before truncation).
Projected int64 `json:"projected,omitempty"`
ProjectionSavedTokens int64 `json:"projection_saved_tokens,omitempty"`
// In-session dedup (#321): results replaced by a dedup marker, and the
// estimated tokens saved.
DedupHits int64 `json:"dedup_hits,omitempty"`
DedupSavedTokens int64 `json:"dedup_saved_tokens,omitempty"`
// Summarization (#321): results replaced by a local-LLM summary, the
// estimated tokens saved, and summarization attempts that fell back to
// truncation.
Summarized int64 `json:"summarized,omitempty"`
SummarizeSavedTokens int64 `json:"summarize_saved_tokens,omitempty"`
SummarizeFallbacks int64 `json:"summarize_fallbacks,omitempty"`
}
GovernorToolStats is the per-tool accounting (for the savings report, #21.6): estimated tokens of the results before and after the governor.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
func NewHandler ¶
func NewHandler(p pool.ServerSource, logger *slog.Logger) *Handler
func NewHandlerWithToolStore ¶
func (*Handler) AttachUpstreamRelay ¶ added in v1.1.1
AttachUpstreamRelay makes the handler receive what the upstreams initiate (server-to-client requests, progress, resource updates) until ctx ends.
func (*Handler) BeginUpstreamCall ¶ added in v1.1.1
func (h *Handler) BeginUpstreamCall(ctx context.Context, server string, clientParams, upstreamParams json.RawMessage) (json.RawMessage, func())
BeginUpstreamCall registers a call to server made on behalf of the client session in ctx, so the server's requests can be routed to that client, and gives it a progress token of the proxy's own: when clientParams (the client's request params) carry _meta.progressToken, the returned params are upstreamParams with _meta.progressToken replaced by a token unique across servers and clients, and the server's progress notifications for it reach this client only, with its original token. The returned func ends the call; it must be called once the upstream answered.
func (*Handler) CachedTools ¶ added in v0.9.2
CachedTools returns a snapshot of the tools known per server name. It is used by the serve listener to register backend tools with the router so tool calls can be routed to the owning server.
func (*Handler) CallLogMiddleware ¶ added in v1.1.1
func (h *Handler) CallLogMiddleware(log *CallLog) Middleware
CallLogMiddleware records every tools/call in log. Install it right after the exposure middleware (so names are already "server.tool") and outside the firewall (so the error text it keeps is already redacted).
func (*Handler) ConfigureRelay ¶ added in v1.1.1
func (h *Handler) ConfigureRelay(servers []*migrate.ServerConfig)
ConfigureRelay sets every server's policy from its config (allow_sampling, roots).
func (*Handler) ConfigureToolSearch ¶ added in v1.1.1
func (h *Handler) ConfigureToolSearch(opts toolsearch.Options) *toolsearch.Index
ConfigureToolSearch replaces the search_tools index with one built from opts and seeds it from the current tool cache. Call it before serving; the returned index can then be switched to hybrid mode with EnableHybrid.
func (*Handler) ExposureMiddleware ¶ added in v1.1.1
func (h *Handler) ExposureMiddleware() Middleware
ExposureMiddleware rewrites a tools/call on a namespaced name ("<server>__<tool>", or its shortened form) into the canonical "<server>.<tool>" form, so every later stage sees the upstream server and tool. It must be the outermost stage. Any other request passes unchanged; so does a name that is not an exposed tool (the handler answers it as before).
func (*Handler) ExposureMode ¶ added in v1.1.1
ExposureMode is the mode of the request's client session: the one decided at its initialize, or the mode of a client without a name before that.
func (*Handler) HandleRequest ¶
HandleRequest runs req through the middleware pipeline registered with Use and, innermost, the handler's own method dispatch.
func (*Handler) HandleServerNotification ¶ added in v1.1.1
func (h *Handler) HandleServerNotification(ctx context.Context, server, method string, params json.RawMessage)
HandleServerNotification routes an upstream notification to the client it belongs to (pool.ServerMessageHandler).
func (*Handler) HandleServerRequest ¶ added in v1.1.1
func (h *Handler) HandleServerRequest(ctx context.Context, server, method string, params json.RawMessage) (json.RawMessage, *errors.JSONRPCError)
HandleServerRequest answers a server-to-client request from an upstream (pool.ServerMessageHandler).
func (*Handler) LoadPersistentToolCache ¶ added in v1.1.1
func (h *Handler) LoadPersistentToolCache()
LoadPersistentToolCache seeds the in-memory tool cache from the persistent toolstore cache. It does no network I/O, so the proxy can serve immediately at startup.
func (*Handler) OnSessionClose ¶ added in v1.1.1
func (h *Handler) OnSessionClose(fn func(*ClientSession))
OnSessionClose registers fn to run when a client session opened with OpenSession ends (the response governor drops the session's spilled results, #319).
func (*Handler) OnToolsChanged ¶ added in v1.1.1
OnToolsChanged registers fn to be called (on the refresh goroutine) with a server's new tool list every time a refresh changes it. `serve` uses it to re-register the server's tools with its router.
func (*Handler) OpenSession ¶ added in v1.1.1
func (h *Handler) OpenSession(notify NotifyFunc) (*ClientSession, func())
OpenSession registers a new client session whose notifications are written with notify, and returns it with the function that unregisters it (call it when the client disconnects). Requests must carry the session in their context (WithClientSession).
func (*Handler) PopulateToolCache ¶ added in v0.5.0
PopulateToolCache loads the persistent cache, then refreshes every server in parallel and waits (bounded by ctx) for all of them. Unlike StartBackgroundRefresh it blocks; it is meant for tools and tests that need a complete cache before continuing.
func (*Handler) RefreshServerTools ¶ added in v1.1.1
RefreshServerTools refreshes the tool list of one server and waits for the result, bounded by ctx and the server's own timeout. A refresh already in progress for that server is joined rather than duplicated.
func (*Handler) ResetManifest ¶
func (h *Handler) ResetManifest()
func (*Handler) SearchIndex ¶ added in v1.1.1
func (h *Handler) SearchIndex() *toolsearch.Index
SearchIndex returns the search_tools index.
func (*Handler) ServerAdded ¶ added in v1.1.1
ServerAdded tells the handler a server joined the pool while it was running (a config reload): its tools are fetched in the background and listing clients are told when they arrive.
func (*Handler) ServerRemoved ¶ added in v1.1.1
ServerRemoved tells the handler a server left the pool: its tools leave the cache and the search index, and listing clients get a tools/list_changed. The persistent tool cache keeps the entry, so a server that comes back is served from it at once.
func (*Handler) Sessions ¶ added in v1.1.1
func (h *Handler) Sessions() []SessionInfo
Sessions lists the open client sessions, oldest first.
func (*Handler) SetDefaultTimeout ¶ added in v0.9.1
SetDefaultTimeout overrides the fallback timeout used when a server has no explicit per-server entry. A zero or negative value is ignored (the 30s default remains in effect).
func (*Handler) SetExposure ¶ added in v1.1.1
SetExposure installs the exposure resolver (nil: every client gets router, as before #322). Call it before serving.
func (*Handler) SetGovernor ¶ added in v1.1.1
SetGovernor gives the governor the handler whose sessions own the spilled results (their results are dropped when they end) and whose servers it splits tool names against.
func (*Handler) SetPolicy ¶ added in v1.1.1
SetPolicy installs the per-tool policy the handler's discovery consults (nil: none) and gives the policy the handler's tool lists.
func (*Handler) SetRelayFirewall ¶ added in v1.1.1
SetRelayFirewall installs the firewall applied to relayed traffic: its redaction on everything relayed in both directions, its injection guard on sampling and elicitation requests.
func (*Handler) SetRelayPolicy ¶ added in v1.1.1
func (h *Handler) SetRelayPolicy(server string, p RelayPolicy)
SetRelayPolicy sets the server-to-client request policy of one server.
func (*Handler) SetTimeout ¶ added in v0.9.1
SetTimeout registers a per-server request timeout. The handler falls back to its default timeout (30s unless changed via SetDefaultTimeout) for any server that has no explicit entry. A zero duration clears the entry.
func (*Handler) SetToolPins ¶ added in v1.1.1
SetToolPins installs the tool pinning state the handler consults (nil: disabled). The handler's configured servers are used to split namespaced tool names.
func (*Handler) SetToolRefreshRetryInterval ¶ added in v1.1.1
SetToolRefreshRetryInterval changes how often the background refresh retries servers without a known tool list. It must be called before StartBackgroundRefresh; a non-positive value is ignored.
func (*Handler) StartBackgroundRefresh ¶ added in v1.1.1
StartBackgroundRefresh starts keeping the tool cache current without ever blocking a request: it refreshes every server's tools/list in parallel (one goroutine per server), refreshes a server again whenever the pool reports a new session (a restart) or a tools/list_changed notification, and periodically retries servers whose tool list is still unknown. It returns immediately; everything stops when ctx ends.
func (*Handler) ToolCount ¶ added in v1.1.1
ToolCount is how many tools the named server is known to have, and whether its tool list is known at all (from the persistent cache or a refresh).
func (*Handler) ToolRefreshStatus ¶ added in v1.1.1
func (h *Handler) ToolRefreshStatus(server string) ToolRefreshStatus
ToolRefreshStatus returns the outcome of server's tool refreshes: the zero value when it was never refreshed.
func (*Handler) Use ¶ added in v1.1.1
func (h *Handler) Use(mws ...Middleware)
Use appends middlewares to the handler's pipeline. The first middleware ever registered is the outermost one; the handler's own method dispatch is always the innermost step. Use is safe to call concurrently with HandleRequest, but a request already in flight keeps the chain it started with, so register middlewares during startup.
type HealthcheckCapability ¶
type HealthcheckCapability struct{}
type Icon ¶ added in v1.1.1
type Icon struct {
Src string `json:"src"`
MimeType string `json:"mimeType,omitempty"`
Sizes []string `json:"sizes,omitempty"`
Theme string `json:"theme,omitempty"`
}
Icon is a visual identifier of a tool, resource or prompt (2025-11-25). mcp-go's Icon lacks the theme field, hence a local type.
type InitializeParams ¶
type InitializeParams struct {
ProtocolVersion string `json:"protocolVersion"`
Capabilities ClientCapabilities `json:"capabilities"`
ClientInfo ClientInfo `json:"clientInfo"`
}
type InitializeResult ¶
type InitializeResult struct {
ProtocolVersion string `json:"protocolVersion"`
Capabilities ServerCapabilities `json:"capabilities"`
ServerInfo ServerInfo `json:"serverInfo"`
Instructions string `json:"instructions,omitempty"`
}
type InjectionGuard ¶ added in v1.1.1
type InjectionGuard struct {
// contains filtered or unexported fields
}
InjectionGuard is the prompt-injection stage of the pipeline (#315). It classifies the decoded, normalized text of every request and of what tools, resources and prompts return (see injection_scan.go), optionally asks a local judge about borderline scores, and applies the policy of the message's direction.
Requests (request_policies; default: block >= 80, quarantine 50-79, log below):
- block → JSON-RPC error, the request is not forwarded;
- quarantine → the payload is saved for review; a tool call gets a tool result with isError: true carrying the quarantine ID, any other method a JSON-RPC error; the request is not forwarded;
- redact → only the matching spans inside string values are replaced by InjectionRedacted (params stay valid JSON; routing fields are kept), then the request is forwarded;
- log → forwarded unchanged.
Responses (response_policies; default: annotate from the threshold, 70, log below):
- annotate → a warning item is prepended to the content (tool result), contents (resource) or messages (prompt); every other byte is kept;
- redact → only the matching spans are replaced;
- block → a tool result becomes isError: true explaining why; a resource or prompt read becomes a JSON-RPC error;
- log → passed through unchanged.
A message the policy lets through unchanged is forwarded byte for byte. A nil *InjectionGuard, or one without a classifier, is disabled.
func NewInjectionGuard ¶ added in v1.1.1
func NewInjectionGuard(cfg *injection.Config) *InjectionGuard
NewInjectionGuard builds a guard from the `injection:` config block. A nil cfg (no block) or `enabled: false` yields a disabled guard.
func (*InjectionGuard) Check ¶ added in v1.1.1
func (g *InjectionGuard) Check(req *Request) *Response
Check classifies req and applies the request policy (see CheckContext).
func (*InjectionGuard) CheckContext ¶ added in v1.1.1
func (g *InjectionGuard) CheckContext(ctx context.Context, req *Request) *Response
CheckContext classifies req and applies the request policy. It returns a non-nil response when the request must not be forwarded (block, quarantine). For the redact action req.Params is rewritten in place and nil is returned.
func (*InjectionGuard) CheckResponse ¶ added in v1.1.1
CheckResponse classifies what req's response returned and applies the response policy. It returns the response to write: resp itself (possibly with a rewritten Result) or a replacement.
func (*InjectionGuard) CheckServerRequest ¶ added in v1.1.1
func (g *InjectionGuard) CheckServerRequest(ctx context.Context, server, method string, params json.RawMessage) (json.RawMessage, *Error)
CheckServerRequest classifies the params of a server-to-client request from server and applies the response policy. It returns the params to relay (possibly rewritten), or a non-nil error when the request must not be relayed.
func (*InjectionGuard) Configure ¶ added in v1.1.1
func (g *InjectionGuard) Configure(cfg *injection.Config)
Configure (re)builds the guard from cfg.
func (*InjectionGuard) Enabled ¶ added in v1.1.1
func (g *InjectionGuard) Enabled() bool
Enabled reports whether requests are classified.
func (*InjectionGuard) Middleware ¶ added in v1.1.1
func (g *InjectionGuard) Middleware() Middleware
Middleware classifies the request before next and the response after it. A blocked or quarantined notification is dropped silently (JSON-RPC forbids replying to notifications).
func (*InjectionGuard) PolicyCount ¶ added in v1.1.1
func (g *InjectionGuard) PolicyCount() int
PolicyCount returns the number of request dispatcher rules in effect.
func (*InjectionGuard) ScansResponses ¶ added in v1.1.1
func (g *InjectionGuard) ScansResponses() bool
ScansResponses reports whether responses are classified.
func (*InjectionGuard) Set ¶ added in v1.1.1
func (g *InjectionGuard) Set(c *injection.Classifier, d *injection.Dispatcher)
Set installs an already-built classifier and request dispatcher, with the default response policy. Either being nil disables the guard.
func (*InjectionGuard) SetOptions ¶ added in v1.1.1
func (g *InjectionGuard) SetOptions(o InjectionGuardOptions)
SetOptions installs the guard's parts.
type InjectionGuardOptions ¶ added in v1.1.1
type InjectionGuardOptions struct {
Classifier *injection.Classifier
Requests *injection.Dispatcher
Responses *injection.Dispatcher
Judge *injection.Referee
MaxScanBytes int
}
InjectionGuardOptions configures a guard from already-built parts (tests, embedders). A nil Classifier or Requests disables the guard; a nil Responses disables response classification.
type Middleware ¶ added in v1.1.1
Middleware wraps a Next with cross-cutting behavior (redaction, injection checks, caching, metering, ...). A middleware may:
- transform the request before calling next,
- short-circuit by returning a response without calling next,
- transform the response returned by next.
Middlewares must be safe for concurrent use: front ends may run several requests through the same chain at once.
func TelemetryMiddleware ¶ added in v1.1.1
func TelemetryMiddleware() Middleware
TelemetryMiddleware is the outermost pipeline stage: it opens the SERVER span for the whole request ("<method> <tool>", per the OTel MCP semantic conventions), records the request-duration and response-size histograms and the requests/errors counters, and tracks in-flight requests. Every other middleware and the upstream call nest under this span as long as they run inside next(ctx, ...) with the ctx this middleware passes down (trace.ContextWithSpan does that automatically for otel.Tracer.Start).
It must be the first entry (outermost) in the slice passed to Handler.Use / mcp.Chain so its span covers the whole pipeline, including the firewall and cache stages.
func Traced ¶ added in v1.1.1
func Traced(name string, mw Middleware) Middleware
Traced wraps a middleware with a named child span ("mcp.middleware.<name>"), used to give each firewall/cache stage its own span under the request's SERVER span (issue #317: "child spans for each middleware"). It is a no-op wrapper cost-wise when telemetry is disabled (tracer().Start returns a no-op span with the parent context unchanged).
type Next ¶ added in v1.1.1
Next is one step of the MCP request pipeline. It receives a (possibly already transformed) request and returns the response that travels back towards the client. A nil response means "nothing to write" (for example a notification).
func Chain ¶ added in v1.1.1
func Chain(inner Next, mws ...Middleware) Next
Chain composes mws around inner. mws[0] is the outermost middleware: it sees the request first and the response last. Nil entries are skipped.
type NotifyFunc ¶ added in v1.1.1
type NotifyFunc func(method string, params json.RawMessage)
NotifyFunc writes one JSON-RPC notification to a client. Front ends implement it on top of their (serialized) writer.
type ParameterMeta ¶ added in v0.5.2
type ParameterMeta struct {
Required bool
Default interface{}
Min interface{}
Max interface{}
Description string
SuggestedValues []string
}
func GetParamMeta ¶ added in v0.5.2
func GetParamMeta(toolName, paramName string) *ParameterMeta
type Policy ¶ added in v1.1.1
type Policy struct {
// contains filtered or unexported fields
}
Per-tool policy (issue #314).
Policy connects a compiled policy.Engine to the pipeline and the handler:
- its Middleware decides every tool call, whatever form it takes (tools/call with a namespaced name, invoke_tool — stdio's gateway tool or serve's method — and serve's namespaced "server.tool" methods), in both front ends, before the response cache and the upstream: deny → JSON-RPC error naming what decided, confirm → ask the user through MCP elicitation, allow → the call proceeds with the deciding rule's injection override (if any) in its context;
- a tool the server does not list in its tools/list is refused when unknown_tools is deny (the default), after one refresh of that list;
- list_tools and search_tools hide denied tools and mark the ones that need confirmation "[confirm]".
Each deny and confirm decision is logged (server, tool, rule, outcome and a SHA-256 of the redacted arguments, never the arguments) and counted in leanproxy.policy.decisions.
func (*Policy) Middleware ¶ added in v1.1.1
func (p *Policy) Middleware() Middleware
Middleware enforces the policy on every tool call. A refused call never reaches the next stage (response cache, firewall, upstream).
func (*Policy) SetRedactor ¶ added in v1.1.1
SetRedactor sets how the arguments shown in a confirmation, and hashed in the audit log, are redacted (the firewall's RedactText).
func (*Policy) SetServerNames ¶ added in v1.1.1
SetServerNames tells the middleware which servers exist, to split namespaced tool names ("server_tool"). Without it the handler's servers are used.
type Prompt ¶
type Prompt struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Arguments []PromptArgument `json:"arguments,omitempty"`
}
type PromptArgument ¶
type PromptsCapability ¶
type PromptsCapability struct {
ListChanged bool `json:"listChanged,omitempty"`
}
type PromptsListParams ¶
type PromptsListParams struct {
Cursor string `json:"cursor,omitempty"`
}
type PromptsListResult ¶
type Redaction ¶ added in v1.1.1
type Redaction struct {
// contains filtered or unexported fields
}
Redaction is the secret-redaction stage of the pipeline. It owns the regex redactor built from the `bouncer:` config block and exposes it both as middlewares (RequestMiddleware, ResponseMiddleware) and as primitives for front ends that need to redact at an extra point (for example before writing to a cache).
The redactor is swapped atomically, so Configure can be called at any time (e.g. on SIGHUP) while requests are in flight. A nil *Redaction is valid and behaves as "redaction disabled".
func NewRedaction ¶ added in v1.1.1
NewRedaction builds a Redaction from cfg. A nil cfg (no `bouncer:` block) enables the built-in patterns; only an explicit `enabled: false` disables redaction.
func (*Redaction) Configure ¶ added in v1.1.1
Configure (re)builds the redactor from cfg with the same defaults as NewRedaction.
func (*Redaction) PatternCount ¶ added in v1.1.1
PatternCount returns the number of active redaction patterns.
func (*Redaction) RedactRequest ¶ added in v1.1.1
RedactRequest redacts req.Params in place, including every nested value (so the `arguments` of tools/call and of an invoke_tool envelope are covered). Params that are not valid JSON are scanned byte by byte instead of being passed through. An error means the params could not be safely redacted and the request must not be forwarded.
func (*Redaction) RedactRequestContext ¶ added in v1.1.1
RedactRequestContext is RedactRequest with a context so redaction counts can be recorded against the request's telemetry span (issue #317).
func (*Redaction) RedactResponse ¶ added in v1.1.1
RedactResponse redacts resp.Result, resp.Error.Message and resp.Error.Data in place.
func (*Redaction) RedactResponseContext ¶ added in v1.1.1
RedactResponseContext is RedactResponse with a context so redaction counts can be recorded against the request's telemetry span (issue #317).
func (*Redaction) RedactText ¶ added in v1.1.1
RedactText redacts a free-form string (log lines, error strings).
func (*Redaction) Redactor ¶ added in v1.1.1
Redactor returns the active redactor, or nil when redaction is disabled.
func (*Redaction) RequestMiddleware ¶ added in v1.1.1
func (r *Redaction) RequestMiddleware() Middleware
RequestMiddleware redacts request params before anything downstream inspects, forwards, caches or persists them. It fails closed: if the params cannot be redacted the client gets a JSON-RPC error carrying RedactionFailedMessage and next is not called.
func (*Redaction) ResponseMiddleware ¶ added in v1.1.1
func (r *Redaction) ResponseMiddleware() Middleware
ResponseMiddleware redacts every response produced downstream — results, error messages and error data alike, whether they come from an upstream server, a gateway tool (list_tools text, error hints) or another middleware. It fails closed: a response that cannot be redacted is replaced by a JSON-RPC error carrying ResponseRedactionFailedMessage.
func (*Redaction) SetRedactor ¶ added in v1.1.1
SetRedactor installs an already-built redactor; nil disables redaction.
type RelayPolicy ¶ added in v1.1.1
type RelayPolicy struct {
// AllowSampling relays sampling/createMessage (servers[].allow_sampling).
AllowSampling bool
// Roots, when non-nil, answers roots/list without asking the client
// (servers[].roots).
Roots []Root
}
RelayPolicy is the per-server policy for server-to-client requests.
type Request ¶
type Request struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
ID interface{} `json:"id"`
}
func (*Request) IsNotification ¶
type RequestFunc ¶ added in v1.1.1
type RequestFunc func(id, method string, params json.RawMessage) error
RequestFunc writes one server-to-client JSON-RPC request with the given id through the front end's serialized writer.
type ResourcesCapability ¶
type ResourcesListParams ¶
type ResourcesListParams struct {
Cursor string `json:"cursor,omitempty"`
}
type ResourcesListResult ¶
type Response ¶
type Response struct {
JSONRPC string `json:"jsonrpc"`
Result json.RawMessage `json:"result,omitempty"`
Error *Error `json:"error,omitempty"`
ID interface{} `json:"id"`
}
type ResponseCache ¶ added in v1.1.1
type ResponseCache struct {
// contains filtered or unexported fields
}
ResponseCache is the opt-in, exact-match `tools/call` response cache (issue #299): off by default, allowlisted read tools only, keyed on the pre-redaction request, bounded LRU by bytes. Unlike the semantic cache it replaces for tools/call, it never does embedding-similarity lookups.
Pipeline ordering (read this before moving the middleware) ¶
ResponseCache.Middleware() MUST be installed OUTERMOST — before (i.e. first in the slice passed to Chain/Handler.Use, ahead of) the firewall's Redaction.ResponseMiddleware() and Redaction.RequestMiddleware():
handler.Use(append([]mcp.Middleware{cache.Middleware()}, firewall.Middlewares()...)...)
Chain makes the first entry outermost, so the request-side effect is that this middleware's func runs and reads req.Params BEFORE Redaction.RequestMiddleware() has a chance to redact them: the cache key is therefore derived from the original, unredacted arguments (required so two calls that differ only in a secret value never share a key — see responsecache.Key).
On the way back, because this middleware is outermost, the *Response it gets from next() has already passed through Redaction.ResponseMiddleware() (which sits just inside it), i.e. it is the REDACTED response. That is exactly what gets stored: the cached value is safe to replay to any future caller.
A cache hit short-circuits before calling next() at all, so on a hit no firewall stage and no upstream call runs for that request — the cached bytes already went through redaction once, when they were stored.
func NewResponseCache ¶ added in v1.1.1
func NewResponseCache(cfg *responsecache.Config) *ResponseCache
NewResponseCache builds a ResponseCache from cfg (the `response_cache:` config block). A nil cfg, or one with Enabled: false (the default), produces a disabled cache: Middleware() then just calls next unconditionally and no memory is allocated for a store.
func (*ResponseCache) Allows ¶ added in v1.1.1
func (rc *ResponseCache) Allows(identity string) bool
Allows reports whether the cache is on and its policy (the allowlist of idempotent read tools) permits caching the tool identified by identity ("server.tool"). Other caches, e.g. `serve`'s semantic cache, use it so that every cache honors the same policy.
With honor_annotations, a tool whose cached definition declares readOnlyHint: true and idempotentHint: true (and not destructiveHint: true) is cacheable too.
func (*ResponseCache) Enabled ¶ added in v1.1.1
func (rc *ResponseCache) Enabled() bool
Enabled reports whether the cache is on and ready to serve lookups.
func (*ResponseCache) Middleware ¶ added in v1.1.1
func (rc *ResponseCache) Middleware() Middleware
Middleware returns the cache stage. See the ResponseCache doc comment for the ordering requirement.
func (*ResponseCache) SetToolSource ¶ added in v1.1.1
func (rc *ResponseCache) SetToolSource(h *Handler)
SetToolSource gives the cache the handler whose tool lists (and their annotations) response_cache.honor_annotations consults.
func (*ResponseCache) Stats ¶ added in v1.1.1
func (rc *ResponseCache) Stats() responsecache.Stats
Stats returns the underlying store's counters, or a zero Stats when the cache is disabled.
type ReturnSchema ¶ added in v0.5.2
type ReturnSchema struct {
Type string `json:"type"`
Description string `json:"description"`
Fields []FieldDescription `json:"fields,omitempty"`
}
type RootsCapability ¶
type RootsCapability struct {
ListChanged bool `json:"listChanged,omitempty"`
}
type ServerCapabilities ¶
type ServerCapabilities struct {
Tools *ToolsCapability `json:"tools,omitempty"`
Resources *ResourcesCapability `json:"resources,omitempty"`
Prompts *PromptsCapability `json:"prompts,omitempty"`
Sampling *ServerSamplingCapability `json:"sampling,omitempty"`
Health *HealthcheckCapability `json:"healthcheck,omitempty"`
}
type ServerInfo ¶
type ServerSamplingCapability ¶
type ServerSamplingCapability struct{}
type SessionInfo ¶ added in v1.1.1
type SessionInfo struct {
ID string `json:"id"`
Client string `json:"client"`
ClientVersion string `json:"client_version,omitempty"`
ProtocolVersion string `json:"protocol_version,omitempty"`
Exposure string `json:"exposure,omitempty"`
Initialized bool `json:"initialized"`
OpenedAt time.Time `json:"opened_at"`
LastCallAt time.Time `json:"last_call_at,omitzero"`
Calls int64 `json:"calls"`
}
SessionInfo describes one connected client, for the admin views.
type StructuredTool ¶ added in v1.1.1
type StructuredTool struct {
Server string `json:"server"`
Tool Tool `json:"tool"`
// Policy is "confirm" when the per-tool policy (#314) asks the user
// before each call to this tool.
Policy string `json:"policy,omitempty"`
}
StructuredTool is one entry of the structuredContent list_tools and search_tools return to clients that negotiated 2025-06-18 or newer: the full upstream tool object (outputSchema, annotations, icons, _meta, ...) and the server that owns it.
type TelemetryCounters ¶ added in v1.1.1
type TelemetryCounters struct {
RequestsTotal int64 `json:"requests_total"`
ErrorsTotal int64 `json:"errors_total"`
Redactions int64 `json:"redactions_total"`
Injections int64 `json:"injection_detections_total"`
CacheHits int64 `json:"cache_hits_total"`
CacheMisses int64 `json:"cache_misses_total"`
PolicyDecisions int64 `json:"policy_decisions_total"`
RateLimitWaits int64 `json:"rate_limit_waits_total"`
ToolPinEvents int64 `json:"tool_pin_events_total"`
InFlight int64 `json:"requests_in_flight"`
// Response governor (#319): tool results seen, results shortened, and
// estimated tokens saved.
GovernedResults int64 `json:"governor_results_total"`
GovernorTruncations int64 `json:"governor_truncations_total"`
GovernorTokensSaved int64 `json:"governor_tokens_saved_total"`
// Field projection (#320): results projected, and estimated tokens
// the projection removed (part of GovernorTokensSaved).
GovernorProjections int64 `json:"governor_projections_total"`
GovernorProjectionTokensSaved int64 `json:"governor_projection_tokens_saved_total"`
// In-session dedup (#321): results replaced by a dedup marker, and
// estimated tokens saved (part of GovernorTokensSaved).
GovernorDedupHits int64 `json:"governor_dedup_hits_total"`
GovernorDedupTokensSaved int64 `json:"governor_dedup_tokens_saved_total"`
// Summarization (#321): results replaced by a local-LLM summary,
// estimated tokens saved (part of GovernorTokensSaved), and
// summarization attempts that fell back to truncation.
GovernorSummarizations int64 `json:"governor_summarizations_total"`
GovernorSummarizationTokensSaved int64 `json:"governor_summarization_tokens_saved_total"`
GovernorSummarizationFallbacks int64 `json:"governor_summarization_fallbacks_total"`
// Schema savings (#324): tools/list responses sent, and their estimated
// tokens with (native) and without (sent) the router's compaction. Both
// are measured from the real marshaled tools/list payload; in
// passthrough/hybrid exposure mode native and sent are the same payload
// (no router compaction happens), so the saving there is legitimately
// zero rather than modeled.
SchemaListings int64 `json:"schema_listings_total"`
SchemaNativeTokens int64 `json:"schema_native_tokens_total"`
SchemaSentTokens int64 `json:"schema_sent_tokens_total"`
// Discovery (#324): calls to the discovery tools (search_tools,
// list_tools, list_servers) and the estimated tokens their results
// cost. This is a real, measured cost, not a saving: discovery trades
// schema tokens for response tokens plus (unmeasured) extra LLM turns.
DiscoveryCalls int64 `json:"discovery_calls_total"`
DiscoveryTokens int64 `json:"discovery_tokens_total"`
}
TelemetryCounters is the plain-value snapshot pkg/metrics exposes on the JSON `/metrics` endpoint alongside (not instead of) the OTLP export.
func TelemetrySnapshot ¶ added in v1.1.1
func TelemetrySnapshot() TelemetryCounters
TelemetrySnapshot returns the current counters. Safe for concurrent use.
type Tool ¶
type Tool struct {
Name string `json:"name"`
// Title is the human-readable display name (2025-06-18).
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
InputSchema json.RawMessage `json:"inputSchema"`
// OutputSchema describes the tool's structuredContent (2025-06-18).
OutputSchema json.RawMessage `json:"outputSchema,omitempty"`
// Annotations are the behavior hints (2025-03-26).
Annotations *ToolAnnotations `json:"annotations,omitempty"`
// Icons are the tool's visual identifiers (2025-11-25).
Icons []Icon `json:"icons,omitempty"`
// Meta is the reserved _meta object (for example MCP Apps UI
// resource references), kept verbatim.
Meta json.RawMessage `json:"_meta,omitempty"`
}
Tool is an MCP tool definition as an upstream server lists it. Every field of the current MCP revision is kept so list_tools / search_tools can hand the full object to clients that negotiated 2025-06-18 or newer.
func (Tool) Destructive ¶ added in v1.1.1
Destructive reports whether the tool explicitly declares destructiveHint: true (and is not read-only, in which case the hint is meaningless per the spec).
type ToolAnnotations ¶ added in v1.1.1
type ToolAnnotations = mcpgo.ToolAnnotation
ToolAnnotations are a tool's behavior hints (title, readOnlyHint, destructiveHint, idempotentHint, openWorldHint). mcp-go's type fits the spec exactly, so it is reused.
type ToolDefinition ¶ added in v0.5.2
type ToolDefinition struct {
Name string `json:"name"`
Description string `json:"description"`
Examples []ToolExample `json:"examples,omitempty"`
Returns ReturnSchema `json:"returns,omitempty"`
Categories []string `json:"categories,omitempty"`
InputSchema json.RawMessage `json:"inputSchema"`
// ReadOnly marks a gateway tool that never changes anything; clients
// that negotiated 2025-03-26 or newer see it as readOnlyHint.
ReadOnly bool `json:"-"`
}
func GetAllToolDefinitions ¶ added in v0.5.2
func GetAllToolDefinitions() []ToolDefinition
func GetToolDefinition ¶ added in v0.5.2
func GetToolDefinition(name string) *ToolDefinition
type ToolExample ¶ added in v0.5.2
type ToolPins ¶ added in v1.1.1
type ToolPins struct {
// contains filtered or unexported fields
}
Tool pinning (issue #310).
ToolPins connects a toolpin.Pinner to the pipeline and the handler:
- every tools/list answer the background refresh fetches is handed to the pinner (Handler.observePins) before it reaches the tool cache, so drift is detected on startup, tools/list_changed and restarts;
- list_tools and search_tools hide the tools the policy blocks and carry a one-line warning about the ones awaiting approval;
- its Middleware refuses calls to blocked tools (block mode) in both front ends, whatever form the call takes: tools/call with a namespaced name, invoke_tool (stdio's gateway tool or serve's method) and serve's namespaced "server.tool" methods.
Invisible and bidi characters are stripped from tool metadata before it reaches a client in every mode (sanitizeTools), pinning on or off.
func NewToolPins ¶ added in v1.1.1
NewToolPins wraps p (nil: pinning disabled) and counts its events in the telemetry.
func (*ToolPins) Middleware ¶ added in v1.1.1
func (g *ToolPins) Middleware() Middleware
Middleware refuses, in block mode, calls to tools that are new, changed or whose server's identity changed, with a JSON-RPC error naming the approval command. The upstream is not called.
func (*ToolPins) SetServerNames ¶ added in v1.1.1
SetServerNames tells the middleware which servers exist, to split namespaced tool names ("server_tool"). Without it the pinned servers are used.
type ToolRefreshStatus ¶ added in v1.1.1
type ToolRefreshStatus struct {
// LastError and LastErrorAt describe the most recent failed refresh.
// They are kept after a later success: Failures tells whether the
// server is failing now.
LastError string
LastErrorAt time.Time
// Failures counts the refreshes that failed since the last success.
Failures int
// LastSuccessAt is when the tool list was last fetched.
LastSuccessAt time.Time
// NextRetryAt is the earliest time of the next periodic retry; zero
// when none is pending. An explicit refresh (a server event, a caller)
// does not wait for it.
NextRetryAt time.Time
}
ToolRefreshStatus is the outcome of a server's tool refreshes so far.
type ToolsCallParams ¶
type ToolsCallParams struct {
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments,omitempty"`
}
type ToolsCallResult ¶
type ToolsCallResult struct {
Content []ContentBlock `json:"content"`
IsError bool `json:"isError,omitempty"`
}
ToolsCallResult is a tools/call result built by LeanProxy itself (text blocks only). Upstream results are relayed as raw JSON and decoded, when needed, with CallToolResult.
type ToolsCapability ¶
type ToolsCapability struct {
ListChanged bool `json:"listChanged,omitempty"`
}
type ToolsListParams ¶
type ToolsListParams struct {
Cursor string `json:"cursor,omitempty"`
}
type ToolsListResult ¶
Source Files
¶
- admin.go
- aggregate.go
- calllog.go
- error_hints.go
- exposure.go
- handlers.go
- injection_relay.go
- injection_scan.go
- middleware.go
- middleware_cache.go
- middleware_firewall.go
- middleware_governor.go
- middleware_injection.go
- middleware_policy.go
- middleware_redact.go
- protocol.go
- relay.go
- search_tools.go
- session_requests.go
- telemetry.go
- tool_defaults.go
- tool_index.go
- toolname.go
- toolpins.go
- toolrefresh.go
- types.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package exposure decides how LeanProxy exposes the upstream tools to one MCP client (issue #322): through its own discovery router (search_tools, list_servers, list_tools, invoke_tool), or directly, every upstream tool listed in tools/list under a namespaced name, so a client with native tool search (Claude Code, the Anthropic and OpenAI APIs, Cursor, ...) can defer and discover the tools itself.
|
Package exposure decides how LeanProxy exposes the upstream tools to one MCP client (issue #322): through its own discovery router (search_tools, list_servers, list_tools, invoke_tool), or directly, every upstream tool listed in tools/list under a namespaced name, so a client with native tool search (Claude Code, the Anthropic and OpenAI APIs, Cursor, ...) can defer and discover the tools itself. |
|
Package governor holds the building blocks of the response token governor (issue #319): its `response:` config block, the per-session spill store that keeps the full (redacted) result of a shortened tool call, the smart text and structural JSON truncation, the read_result retrieval primitives (paging, grep, a JSONPath subset), and the field projection of #320 (project.go).
|
Package governor holds the building blocks of the response token governor (issue #319): its `response:` config block, the per-session spill store that keeps the full (redacted) result of a shortened tool call, the smart text and structural JSON truncation, the read_result retrieval primitives (paging, grep, a JSONPath subset), and the field projection of #320 (project.go). |
|
Package responsecache implements the opt-in, exact-match tools/call response cache (issue #299): a bounded-by-bytes LRU keyed on the pre-redaction request, storing the redacted response.
|
Package responsecache implements the opt-in, exact-match tools/call response cache (issue #299): a bounded-by-bytes LRU keyed on the pre-redaction request, storing the redacted response. |