mcp

package
v0.4.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 29, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const MCPProtocolVersion = "2025-11-25"

MCPProtocolVersion is the MCP protocol version used only by the plain JSON-RPC fallback path in this package. Streamable and SSE transports are SDK-managed and negotiate protocol versions internally.

Variables

This section is empty.

Functions

func BuildMCPTextResponse added in v0.3.0

func BuildMCPTextResponse(text string) map[string]any

BuildMCPTextResponse returns a raw MCP response map with a single text content item.

func ConvertToCallToolResult added in v0.1.16

func ConvertToCallToolResult(data any) (*sdk.CallToolResult, error)

ConvertToCallToolResult converts backend result data to SDK CallToolResult format. The backend returns a JSON object with a "content" field containing an array of content items.

Fast path: when data is already a deserialized map[string]any (the common case after json.Unmarshal(response.Result, &any)), the function skips the redundant marshal/unmarshal round-trip and works with the map directly.

func NewErrorCallToolResult added in v0.2.22

func NewErrorCallToolResult(err error) (*sdk.CallToolResult, any, error)

NewErrorCallToolResult creates a standard error CallToolResult with the error message included as text content.

func NormalizeInputSchema

func NormalizeInputSchema(schema map[string]any, toolName string) map[string]any

NormalizeInputSchema ensures tool input schemas are valid for the MCP SDK The MCP SDK requires that object type schemas have a "properties" field, even if it's empty. This function normalizes schemas to meet that requirement.

Returns a normalized copy of the schema, never modifies the original.

func PaginateAll added in v0.3.26

func PaginateAll[T any](maxPages int, fetch func(cursor string) ([]T, string, error)) ([]T, error)

PaginateAll is the canonical cursor-based pagination algorithm shared across the codebase. It collects all items from a sequence of paginated fetch calls.

fetch is called with a cursor string (empty string for the first call) and must return the items for that page, the cursor for the next page (empty when done), and any error. PaginateAll stops as soon as a page returns an empty next-cursor.

maxPages caps the total number of fetch calls to prevent runaway loops. It must be a positive integer; a value of 0 or negative disables the cap (no page limit), which should only be used in tests or when the caller enforces its own limit. Returns an error if the cap is reached or if the same cursor is returned twice (cycle).

func ParseToolArguments added in v0.1.16

func ParseToolArguments(req *sdk.CallToolRequest) (map[string]any, error)

ParseToolArguments extracts and unmarshals tool arguments from a CallToolRequest. Returns the parsed arguments as a map, or an error if parsing fails.

Types

type AgentTagsSnapshot added in v0.1.10

type AgentTagsSnapshot struct {
	Secrecy   []string
	Integrity []string
}

AgentTagsSnapshot contains agent secrecy/integrity tag snapshots for log enrichment.

func GetAgentTagsSnapshotFromContext added in v0.1.14

func GetAgentTagsSnapshotFromContext(ctx context.Context) (*AgentTagsSnapshot, bool)

GetAgentTagsSnapshotFromContext extracts the agent DIFC tag snapshot from the request context. Used by guards (e.g., write-sink) that need the agent's current labels to mirror onto resources.

type CallToolParams

type CallToolParams struct {
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments,omitempty"`
}

CallToolParams represents parameters for calling a tool.

This is a local type rather than an alias for the SDK's CallToolParams because the gateway's plain JSON-RPC transport path needs to marshal/unmarshal tool call parameters from raw JSON without importing the SDK's typed params (which use json.RawMessage for Arguments). The local type uses map[string]any for Arguments, matching the gateway's internal representation and simplifying the marshal/unmarshal roundtrip in callParamMethod. See callTool in connection.go for the bridge to the SDK type.

type Connection

type Connection struct {
	// contains filtered or unexported fields
}

Connection represents a connection to an MCP server using the official SDK

func NewConnection

func NewConnection(ctx context.Context, serverID, command string, args []string, env map[string]string) (*Connection, error)

NewConnection creates a new MCP connection using the official SDK

func NewHTTPConnection

func NewHTTPConnection(ctx context.Context, serverID, url string, headers map[string]string, oidcProvider *oidc.Provider, oidcAudience string, keepAlive time.Duration, connectTimeout time.Duration) (*Connection, error)

NewHTTPConnection creates a new HTTP-based MCP connection with transport fallback For HTTP servers that are already running, we connect and initialize a session

This function implements a fallback strategy for HTTP transports:

  1. Try standard transports in order: a. Streamable HTTP (2025-03-26 spec) using SDK's StreamableClientTransport b. SSE (2024-11-05 spec) using SDK's SSEClientTransport c. Plain JSON-RPC 2.0 over HTTP POST as final fallback

Custom headers (e.g. Authorization) are injected into every outgoing request via a custom http.RoundTripper, so the SDK transports are used even when authentication headers are configured.

When oidcProvider is non-nil, a GitHub Actions OIDC token is dynamically acquired and injected as Authorization: Bearer on every request, overriding any static Authorization header from the headers map.

This ensures compatibility with all types of HTTP MCP servers.

func (*Connection) BackendHasPromptsCapability added in v0.3.31

func (c *Connection) BackendHasPromptsCapability() bool

BackendHasPromptsCapability reports whether the backend declared prompt support in its MCP initialize response. Only SDK-based connections (streamable, SSE, stdio) expose this information; plain JSON-RPC connections always return false because their initialize response is not parsed into a typed capability struct.

In the MCP specification, a nil Capabilities.Prompts field means the server did not include a "prompts" entry in its capabilities object — i.e. it explicitly does not support prompts. A non-nil value (even an empty struct) signals prompt support.

Callers should skip prompts/list on backends where this returns false to avoid issuing an unsupported request that could corrupt an SDK session via an EOF response.

func (*Connection) Close

func (c *Connection) Close() error

Close closes the connection

func (*Connection) GetHTTPHeaders

func (c *Connection) GetHTTPHeaders() map[string]string

GetHTTPHeaders returns the HTTP headers for this connection

func (*Connection) GetHTTPURL

func (c *Connection) GetHTTPURL() string

GetHTTPURL returns the HTTP URL for this connection

func (*Connection) IsHTTP

func (c *Connection) IsHTTP() bool

IsHTTP returns true if this is an HTTP connection

func (*Connection) SendRequest

func (c *Connection) SendRequest(method string, params any) (*Response, error)

SendRequest sends a JSON-RPC request and waits for the response The serverID parameter is used for logging to associate the request with a backend server

func (*Connection) SendRequestWithServerID

func (c *Connection) SendRequestWithServerID(ctx context.Context, method string, params any, serverID string) (*Response, error)

SendRequestWithServerID sends a JSON-RPC request with server ID for logging The ctx parameter is used to extract session ID for HTTP MCP servers

func (*Connection) ServerInfo added in v0.2.18

func (c *Connection) ServerInfo() (name, version string)

ServerInfo returns the backend's name and version from the MCP initialize handshake. Returns ("", "") when no SDK session is available (plain JSON-RPC transport).

type ContentItem

type ContentItem struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

ContentItem represents a content item in tool responses

type ContextKey

type ContextKey string

ContextKey for session ID

const AgentTagsSnapshotContextKey ContextKey = "awmg-agent-tags-snapshot"

AgentTagsSnapshotContextKey stores a per-request snapshot of agent DIFC tags for enriched logging.

const SessionIDContextKey ContextKey = "awmg-session-id"

SessionIDContextKey is used to store MCP session ID in context This is the same key used in the server package to avoid circular dependencies

type HTTPTransportType

type HTTPTransportType string

HTTPTransportType represents the type of HTTP transport being used

const (
	// HTTPTransportStreamable uses the streamable HTTP transport (2025-03-26 spec)
	HTTPTransportStreamable HTTPTransportType = "streamable"
	// HTTPTransportSSE uses the SSE transport (2024-11-05 spec)
	HTTPTransportSSE HTTPTransportType = "sse"
	// HTTPTransportPlainJSON uses plain JSON-RPC 2.0 over HTTP POST (non-standard)
	HTTPTransportPlainJSON HTTPTransportType = "plain-json"
)

type Request

type Request struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      any             `json:"id,omitempty"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

Request represents a JSON-RPC 2.0 request

type Response

type Response struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      any             `json:"id"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *ResponseError  `json:"error,omitempty"`
}

Response represents a JSON-RPC 2.0 response

type ResponseError

type ResponseError struct {
	Code    int             `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

ResponseError represents a JSON-RPC 2.0 error

type Tool

type Tool struct {
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	InputSchema map[string]any `json:"inputSchema"`
}

Tool represents an MCP tool definition

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL