mcpx

package
v0.0.0-...-336f9e3 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mcpx serves an application's tools to MCP clients over the Model Context Protocol: one endpoint at /mcp, Streamable HTTP without sessions, behind a bearer key.

It wraps the official Go SDK (github.com/modelcontextprotocol/go-sdk) with what every application would otherwise repeat:

  • the key check of the cockpit summary: the key is the application's own, read from a file it names; without a key the path answers 404, a wrong key 401, and the comparison takes constant time. A key in the query string is never read;
  • limits: the request body size and a deadline for each tool call;
  • recovery: a panicking tool answers an error and the process keeps running;
  • one report per tool call (tool, target, result, duration) for the application's log, which never carries the call's arguments;
  • errors a model can act on: only an Error reaches the client in its own words; any other error, which may quote a database or a file, is replaced by a general message and handed to the report instead;
  • an in-memory client session for tests (Server.Connect; package mcpxtest builds on it).

The tools are the application's: what they read and change, and that they go through the same checks as its web API. The package composes no tool names and no environment variable.

Example
package main

import (
	"context"
	"net/http"

	"github.com/modelcontextprotocol/go-sdk/mcp"

	"github.com/RCooLeR/kit/mcpx"
)

type noteArgs struct {
	ID string `json:"id" jsonschema:"the note's ID, from list_notes"`
}

type note struct {
	ID   string `json:"id"`
	Text string `json:"text"`
}

func main() {
	server := mcpx.New(mcpx.Options{
		Name: "notes", Version: "1.0.0",
		Key:    "the key read from the application's key file",
		OnCall: func(call mcpx.Call) { /* one log line: call.Tool, call.Target, call.Result, call.Duration */ },
	})
	mcpx.AddTool(server, mcpx.Read("get_note", "Reads one note by its ID; list_notes gives the IDs."),
		func(_ context.Context, _ *mcp.CallToolRequest, args noteArgs) (*mcp.CallToolResult, note, error) {
			if args.ID != "1" {
				return nil, note{}, mcpx.NotFound("note %s does not exist", args.ID)
			}
			return nil, note{ID: "1", Text: "first"}, nil
		})
	mux := http.NewServeMux()
	mux.Handle(mcpx.Path, server.Handler())
}

Index

Examples

Constants

View Source
const (
	DefaultMaxBodyBytes = 1 << 20
	DefaultTimeout      = 30 * time.Second
)

Defaults of the limits in Options.

View Source
const Path = "/mcp"

Path is where the endpoint is served.

Variables

This section is empty.

Functions

func AddTool

func AddTool[In, Out any](s *Server, tool *mcp.Tool, handler mcp.ToolHandlerFor[In, Out])

AddTool adds a tool with a typed handler, as the SDK's mcp.AddTool does, and wraps the handler: a panic or an error other than Error reaches the client as a general message, and the report of the call gets the cause.

func Conflict

func Conflict(format string, args ...any) error

Conflict reports a change the object's current state does not allow.

func Errorf

func Errorf(code, format string, args ...any) error

Errorf makes an Error with the given code.

func Invalid

func Invalid(format string, args ...any) error

Invalid reports arguments the application refuses, as its web API would with 400 or 422.

func NotFound

func NotFound(format string, args ...any) error

NotFound reports an object that does not exist.

func Read

func Read(name, description string) *mcp.Tool

Read describes a tool that only reads the application's data.

func Target

func Target(ctx context.Context, id string)

Target names the object a tool call acts on, such as the ID of a delivery it retries, for the report of the call. The last name given wins.

func Write

func Write(name, description string, effect Effect) *mcp.Tool

Write describes a tool that changes data without deleting any.

Types

type Call

type Call struct {
	Tool string
	// ReadOnly is the tool's read-only annotation, so the log can tell reads from writes.
	ReadOnly bool
	// Target is what the tool named with [Target], such as the ID of the object it changed.
	Target   string
	Result   Result
	Duration time.Duration
	// Err is the cause of a refused or failed call.
	Err error
}

Call reports one tool call. It never holds the call's arguments.

type Effect

type Effect struct {
	// Idempotent: calling the tool again with the same arguments changes nothing more.
	Idempotent bool
	// OpenWorld: the tool reaches outside the application, such as sending a message or starting
	// a download.
	OpenWorld bool
}

Effect says what a write tool does beyond changing the application's own data.

type Error

type Error struct {
	// Code is a short word for the kind, such as "not_found", or the web API's code for the case.
	Code    string
	Message string
}

Error is an error the client sees in full: what went wrong in words a model can act on, never a secret. Return it from a tool for wrong arguments, a missing object or a refused change.

func (*Error) Error

func (e *Error) Error() string

Error returns the code and the message.

type Options

type Options struct {
	// Name and Version identify the application to clients, such as its token and build version.
	Name    string
	Version string
	// Title is a display name; Instructions tell a model how the tools fit together. Both optional.
	Title        string
	Instructions string
	// Key is the bearer key, read from the application's key file. Empty makes the path answer 404.
	Key string
	// MaxBodyBytes limits a request body (413 above it); zero means DefaultMaxBodyBytes.
	MaxBodyBytes int64
	// Timeout is the deadline of one tool call; zero means DefaultTimeout.
	Timeout time.Duration
	// OnCall receives one report per tool call, for a log line; nil drops them.
	OnCall func(Call)
	// OnError receives a panic outside a tool call, for a log line; nil drops it.
	OnError func(error)
}

Options configure a Server.

type Result

type Result string

Result is how a tool call ended.

const (
	// ResultOK: the tool did what it was asked.
	ResultOK Result = "ok"
	// ResultRefused: the call was answered with an error the client sees in full: arguments that
	// do not fit the tool, an unknown tool, or an [Error] such as "not found".
	ResultRefused Result = "refused"
	// ResultFailed: the tool failed or panicked; the client sees a general message and Err holds
	// the cause.
	ResultFailed Result = "failed"
)

Results of a tool call.

type Server

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

Server is an application's MCP server: add its tools with AddTool, then mount Server.Handler at Path.

func New

func New(opts Options) *Server

New makes a server without tools.

func (*Server) Connect

func (s *Server) Connect(ctx context.Context) (*mcp.ClientSession, error)

Connect opens a client session on the server in memory, for tests. Calls go through the same deadline, recovery and reports as over HTTP; there is no key check. Close the session when done.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler serves Path: the key check, then the SDK's Streamable HTTP transport without sessions, answering JSON. Mount it for every method; GET and DELETE answer 405.

The SDK refuses a request that reaches the server on a loopback address with a Host header that is not loopback (DNS rebinding protection). A reverse proxy on the same machine must therefore forward the original loopback Host, or clients use the application's own address.

Directories

Path Synopsis
Package mcpxtest helps an application test its MCP tools: an in-memory client session, tool calls read as text, and a check that no output carries a secret.
Package mcpxtest helps an application test its MCP tools: an in-memory client session, tool calls read as text, and a check that no output carries a secret.

Jump to

Keyboard shortcuts

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