Documentation
¶
Overview ¶
Package serve is the runtime of cloudmcp. It runs MCP servers, defined with the official Go SDK, as AWS Lambda functions behind AWS API Gateway, or as long-running HTTP servers.
The package does not depend on AWS CDK, the Lambda function's main imports it:
func main() {
lambda.Start(serve.Handler(server.New))
}
Index ¶
- Constants
- func DefaultTokenInfo(id *Identity) *auth.TokenInfo
- func HTTPHandler(f ServerFactory, opts ...Option) http.Handler
- func IsStandardHeader(key string) bool
- func ListenAndServe(addr string, f ServerFactory, opts ...Option) error
- func NewInvocation(inv Invocation) ([]byte, error)
- func NewRequestV1(ctx context.Context, evt *events.APIGatewayProxyRequest) (*http.Request, error)
- func NewRequestV2(ctx context.Context, evt *events.APIGatewayV2HTTPRequest) (*http.Request, error)
- func WithIdentityContext(ctx context.Context, id *Identity) context.Context
- type Identity
- type Invocation
- type LambdaHandler
- type Option
- func WithDebug() Option
- func WithHTTPOptions(opts *mcp.StreamableHTTPOptions) Option
- func WithIdentity(f func(*Identity) *auth.TokenInfo) Option
- func WithJSONLogs(level slog.Leveler) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMetrics(namespace string) Option
- func WithResourceServer(rs ResourceServer) Option
- func WithVerifier(verifier auth.TokenVerifier) Option
- type ResourceServer
- type ServerFactory
Constants ¶
const DefaultMetadataPath = "/.well-known/oauth-protected-resource"
DefaultMetadataPath is the well-known path of protected resource metadata (RFC 9728).
Variables ¶
This section is empty.
Functions ¶
func DefaultTokenInfo ¶
DefaultTokenInfo maps the identity into go-sdk's auth.TokenInfo:
- UserID is the first non-empty of the authorizer context keys "principal", "sub", "principalId", the JWT "sub" claim or IAM principal.
- Scopes are the authorizer context key "scope" or "scopes" (space separated string or list), or the JWT scopes.
- Extra holds every key of the authorizer context, JWT claims at "claims" and path parameters at "path".
TokenInfo is produced for anonymous callers too, its UserID is empty.
func HTTPHandler ¶
func HTTPHandler(f ServerFactory, opts ...Option) http.Handler
HTTPHandler returns http.Handler serving MCP servers of the factory. It is the core of both Lambda (Handler) and server (ListenAndServe) modes.
func IsStandardHeader ¶
IsStandardHeader reports whether the header is a standard MCP header mirroring the message (Mcp-Method, Mcp-Name, Mcp-Param-*), which the dispatcher forwards to the worker.
func ListenAndServe ¶
func ListenAndServe(addr string, f ServerFactory, opts ...Option) error
ListenAndServe runs MCP servers of the factory as long-running HTTP server.
func NewInvocation ¶
func NewInvocation(inv Invocation) ([]byte, error)
NewInvocation encodes the invocation event of the worker function.
func NewRequestV1 ¶
NewRequestV1 converts API Gateway event (payload format 1.0) to HTTP request with the caller's Identity in the context.
func NewRequestV2 ¶
NewRequestV2 converts API Gateway event (payload format 2.0) to HTTP request with the caller's Identity in the context.
Types ¶
type Identity ¶
type Identity struct {
// Context of Lambda authorizer (payload 1.0: RequestContext.Authorizer,
// payload 2.0: RequestContext.Authorizer.Lambda).
Authorizer map[string]any
// Claims and scopes of JWT (or Cognito) authorizer.
Claims map[string]any
Scopes []string
// IAM principal (user ARN) of IAM authorizer.
Principal string
// Path parameters of the route (e.g. {instance} of /{instance}).
PathParameters map[string]string
}
Identity of the caller as established by AWS API Gateway. The adapter builds it from the request's context, the client cannot change it.
func IdentityFromContext ¶
IdentityFromContext returns identity established by API Gateway, nil when the request did not come through API Gateway.
type Invocation ¶
type Invocation struct {
// JSON-RPC message
Message json.RawMessage `json:"message"`
// Negotiated MCP protocol version (Mcp-Protocol-Version)
ProtocolVersion string `json:"protocolVersion,omitempty"`
// Standard MCP headers of the client's request (Mcp-Method, Mcp-Name,
// Mcp-Param-*). Since protocol 2026-07-28 the worker validates them
// against the message, Mcp-Method and Mcp-Name are derived from the
// message if absent, Mcp-Param-* must be forwarded.
Header map[string]string `json:"header,omitempty"`
// The caller's identity
TokenInfo *auth.TokenInfo `json:"tokenInfo,omitempty"`
}
Invocation is the event of the dispatcher invoking the worker function. The worker's IAM policy grants invoke only to the dispatcher, the worker trusts the caller's TokenInfo established by the dispatcher.
type LambdaHandler ¶
LambdaHandler is the entry point of Lambda function, use it with lambda.Start.
func Handler ¶
func Handler(f ServerFactory, opts ...Option) LambdaHandler
Handler returns Lambda function handler serving MCP servers of the factory.
func main() {
lambda.Start(serve.Handler(server.New))
}
The handler accepts API Gateway events of payload format 1.0 (events.APIGatewayProxyRequest) and 2.0 (events.APIGatewayV2HTTPRequest), detected from the event, and direct invocations by the dispatcher. Servers are stateless and respond with JSON (no event streams).
type Option ¶
type Option func(*config)
Option configures the runtime.
func WithDebug ¶
func WithDebug() Option
WithDebug logs JSON-RPC method and id of each request at debug level. Parameters are never logged, they may hold user data.
func WithHTTPOptions ¶
func WithHTTPOptions(opts *mcp.StreamableHTTPOptions) Option
WithHTTPOptions overrides options of the go-sdk streamable HTTP handler. Lambda functions default to stateless JSON responses, Lambda cannot keep sessions or stream events. Server mode defaults to the go-sdk defaults.
func WithIdentity ¶
WithIdentity overrides the mapping of the gateway's identity (authorizer context and path parameters) into go-sdk's auth.TokenInfo, which tools read from req.Extra.TokenInfo. The default is DefaultTokenInfo. Returning nil leaves the request without TokenInfo.
func WithJSONLogs ¶
WithJSONLogs configures structured JSON logs to stdout at the given level, it also becomes the default slog logger of the process.
func WithLogger ¶
WithLogger sets the logger of the runtime and the go-sdk handler. The default is slog.Default().
func WithMetrics ¶
WithMetrics emits CloudWatch metrics of every MCP request using the Embedded Metric Format (EMF), written to stdout (Lambda's log).
Metrics "Requests" (Count), "Errors" (Count) and "Latency" (Milliseconds) have dimensions [Method] and [Method, Tool] (tools/call). A request is an error if HTTP status is not 2xx, the JSON-RPC response is an error or the tool result has isError.
func WithResourceServer ¶
func WithResourceServer(rs ResourceServer) Option
WithResourceServer enables MCP authorization compliance (see ResourceServer).
func WithVerifier ¶
func WithVerifier(verifier auth.TokenVerifier) Option
WithVerifier verifies bearer tokens within the function, using go-sdk's auth.RequireBearerToken. Use it when the route is public (server mode, or public API Gateway route) and the function is the resource server. Path parameters of the gateway are added to TokenInfo.Extra["path"].
type ResourceServer ¶
type ResourceServer struct {
// Metadata served at Path (required).
Metadata *oauthex.ProtectedResourceMetadata
// Path of the metadata, default is DefaultMetadataPath. Sub-paths are
// served too (RFC 9728 §3.1, e.g. /.well-known/oauth-protected-resource/mcp).
Path string
// Absolute URL of the metadata used by the challenge, default is
// https://{Host}{Path} of the request.
URL string
// Scopes required to access the server, advertised by the challenge.
Scopes []string
// Authenticated tells whether the gateway authenticated the caller,
// default is TokenInfo with non-empty UserID. Use it with an annotating
// authorizer, e.g. checking info.Extra["decision"].
Authenticated func(*auth.TokenInfo) bool
}
ResourceServer configures MCP authorization compliance: the function serves protected resource metadata (RFC 9728) and answers unauthenticated requests with 401 and "WWW-Authenticate: Bearer resource_metadata=...", so that OAuth-capable MCP clients discover how to authenticate.
API Gateway's own 401 cannot carry the challenge, the route shall either be public (use WithVerifier to verify bearer tokens in the function) or be protected by an annotating Lambda authorizer that always allows the request and passes its decision in the context (see Authenticated).
type ServerFactory ¶
ServerFactory returns MCP server for the request. It is the argument of mcp.NewStreamableHTTPHandler. Use Static for the server shared by all requests, or Filter to choose tools per request.
func Filter ¶
Filter chooses tools of the server per request. The server is built once, with all tools, the predicate decides which tools the caller sees in tools/list and may call with tools/call. The predicate receives go-sdk's TokenInfo of the request (nil if none).
readonly := func(t *mcp.Tool, info *auth.TokenInfo) bool {
if info != nil && slices.Contains(info.Scopes, "write") {
return true
}
return t.Annotations != nil && t.Annotations.ReadOnlyHint
}
lambda.Start(serve.Handler(serve.Filter(server, readonly)))
Calls of hidden tools fail as calls of unknown tools. Filter installs receiving middleware to the server, call it once per server.
func Static ¶
func Static(server *mcp.Server) ServerFactory
Static returns the factory that serves the same server for every request.
func Tool ¶
func Tool[In, Out any](tool *mcp.Tool, handler mcp.ToolHandlerFor[In, Out]) ServerFactory
Tool returns the factory of MCP server with the single typed tool. Use it for worker functions behind the dispatcher, one tool per function:
func main() {
lambda.Start(serve.Handler(
serve.Tool(&mcp.Tool{Name: "sayer", Description: "says hi"}, sayer.Sayer),
))
}
The server's implementation name is the tool's name, the version is the version of the main module.