Documentation
¶
Overview ¶
Package argon is a small framework for building MCP (Model Context Protocol) servers in Go.
s := argon.New("notes")
argon.Tool(s, "add_note", "Save a note", func(ctx context.Context, in struct {
Text string `json:"text" jsonschema:"Note text"`
}) (string, error) {
return save(in.Text)
})
s.Run()
Argon is built on the official Go SDK but never exposes its types.
Example ¶
A complete server: one tool, served over stdio by default or over Streamable HTTP with --http :8080.
package main
import (
"context"
"log"
"go.xchunk.org/argon"
)
func main() {
type GreetInput struct {
Name string `json:"name" jsonschema:"who to greet"`
}
s := argon.New("hello")
argon.Tool(s, "greet", "Say hi", func(ctx context.Context, in GreetInput) (string, error) {
return "Hi, " + in.Name + "!", nil
}, argon.ReadOnly())
if err := s.Run(); err != nil {
log.Fatal(err)
}
}
Output:
Index ¶
- Constants
- Variables
- func Prompt[In any](s *Server, name, description string, ...)
- func Resource(s *Server, uri, name, description string, ...)
- func ResourceTemplate[P any](s *Server, uriTemplate, name, description string, ...)
- func Tool[In, Out any](s *Server, name, description string, h func(context.Context, In) (Out, error), ...)
- type Annotations
- type Content
- type Handler
- type Identity
- type ImageContent
- type Middleware
- type Option
- type PromptMessage
- type PromptOption
- type Request
- type ResourceContents
- type ResourceLink
- type ResourceOption
- type Result
- type Role
- type Server
- func (s *Server) Err() error
- func (s *Server) Handler() (http.Handler, error)
- func (s *Server) ResourceMetadata() (path string, h http.Handler, err error)
- func (s *Server) Run() error
- func (s *Server) RunHTTP(ctx context.Context, addr string) error
- func (s *Server) RunStdio(ctx context.Context) error
- type TextContent
- type ToolMeta
- type ToolOption
- func Destructive() ToolOption
- func Idempotent() ToolOption
- func OpenWorld() ToolOption
- func ReadOnly() ToolOption
- func Scopes(scopes ...string) ToolOption
- func Title(t string) ToolOption
- func ToolMaxOutput(n int) ToolOption
- func ToolTimeout(d time.Duration) ToolOption
- func With(mws ...Middleware) ToolOption
Examples ¶
Constants ¶
const ( DefaultTimeout = 60 * time.Second DefaultMaxOutput = 1 << 20 // 1 MiB )
Safe defaults applied when not overridden.
const EnvHTTP = "ARGON_HTTP"
EnvHTTP selects the HTTP transport when set to a listen address.
Variables ¶
var ErrInvalidArguments = errs.InvalidArguments
ErrInvalidArguments reports rejected arguments. Missing, unknown and malformed prompt arguments are rejected with it automatically before the handler runs; a prompt handler may also return it (possibly wrapped) to reject input itself. The client receives the protocol's "invalid params" error. Invalid tool input wraps it as well, reported as an isError result.
var ErrResourceNotFound = errs.ResourceNotFound
ErrResourceNotFound reports that a requested resource does not exist. Return it (possibly wrapped) from a resource handler; the client receives the protocol's "resource not found" error. Reads of URIs that match no resource, or whose template variables do not decode, report it too.
Functions ¶
func Prompt ¶
func Prompt[In any](s *Server, name, description string, h func(context.Context, In) ([]PromptMessage, error), opts ...PromptOption)
Prompt registers a prompt template on s.
The prompt's arguments are the fields of In, a struct: names come from json tags, descriptions from jsonschema tags, and fields without omitempty are required. Clients send arguments as strings; they are converted to the field types (string, integers, floats, bool) and validated before the handler runs. Use struct{} for a prompt without arguments.
type ReviewArgs struct {
Code string `json:"code" jsonschema:"code to review"`
Language string `json:"language,omitempty"`
}
argon.Prompt(s, "code_review", "Review a piece of code",
func(ctx context.Context, a ReviewArgs) ([]argon.PromptMessage, error) {
return []argon.PromptMessage{
argon.UserMessage("Review this " + a.Language + " code:\n" + a.Code),
}, nil
})
Prompts get the same safe defaults as tools (timeout, output limit, panic recovery) and may require scopes. Tool middleware does not apply. Registration errors are reported by Run*.
Example ¶
package main
import (
"context"
"go.xchunk.org/argon"
)
func main() {
type ReviewArgs struct {
Code string `json:"code" jsonschema:"code to review"`
Language string `json:"language,omitempty" jsonschema:"programming language"`
}
s := argon.New("review")
argon.Prompt(s, "code_review", "Review a piece of code",
func(ctx context.Context, a ReviewArgs) ([]argon.PromptMessage, error) {
return []argon.PromptMessage{
argon.UserMessage("Review this " + a.Language + " code:\n" + a.Code),
}, nil
}, argon.PromptTitle("Code review"))
}
Output:
func Resource ¶
func Resource(s *Server, uri, name, description string, h func(context.Context) (ResourceContents, error), opts ...ResourceOption)
Resource registers a resource with a fixed, absolute URI on s.
argon.Resource(s, "file:///readme.md", "readme", "Project readme",
func(ctx context.Context) (argon.ResourceContents, error) {
return argon.TextResource(readme), nil
}, argon.MIMEType("text/markdown"))
Resources get the same safe defaults as tools (timeout, output limit, panic recovery) and may require scopes. Tool middleware does not apply. Registration errors are reported by Run*.
Example ¶
package main
import (
"context"
"go.xchunk.org/argon"
)
func main() {
s := argon.New("docs")
argon.Resource(s, "file:///readme.md", "readme", "Project readme",
func(ctx context.Context) (argon.ResourceContents, error) {
return argon.TextResource("# Project"), nil
}, argon.MIMEType("text/markdown"))
}
Output:
func ResourceTemplate ¶
func ResourceTemplate[P any](s *Server, uriTemplate, name, description string, h func(context.Context, P) (ResourceContents, error), opts ...ResourceOption)
ResourceTemplate registers a family of resources described by an RFC 6570 URI template, such as "notes://{id}". Template variables are decoded into P, a struct whose json field names match the variable names; values are converted to the field types (string, integers, floats, bool) and validated like tool input. A URI whose variables do not decode is reported to the client as not found.
Variables arrive percent-decoded, so they may contain "/" or "..": treat them as untrusted input, for example before using one as a file path.
type NoteRef struct {
ID int `json:"id"`
}
argon.ResourceTemplate(s, "notes://{id}", "note", "A note by id",
func(ctx context.Context, ref NoteRef) (argon.ResourceContents, error) {
n, ok := notes[ref.ID]
if !ok {
return argon.ResourceContents{}, argon.ErrResourceNotFound
}
return argon.TextResource(n), nil
})
Example ¶
Template variables decode into a struct; a URI whose variables do not decode (here, a non-numeric id) reads as not found.
package main
import (
"context"
"go.xchunk.org/argon"
)
func main() {
type NoteRef struct {
ID int `json:"id"`
}
notes := map[int]string{1: "buy milk"}
s := argon.New("notes")
argon.ResourceTemplate(s, "notes://{id}", "note", "A note by id",
func(ctx context.Context, ref NoteRef) (argon.ResourceContents, error) {
n, ok := notes[ref.ID]
if !ok {
return argon.ResourceContents{}, argon.ErrResourceNotFound
}
return argon.TextResource(n), nil
}, argon.MIMEType("text/plain"))
}
Output:
func Tool ¶
func Tool[In, Out any](s *Server, name, description string, h func(context.Context, In) (Out, error), opts ...ToolOption)
Tool registers a typed tool on s.
In must be a struct, a pointer to a struct or a map with string keys; its JSON Schema is inferred from json and jsonschema struct tags, and input is validated against it. Other input types are reported as registration errors. Out may be a string, *Result or any JSON-serializable type. A returned error becomes an isError result, not a protocol failure.
Tool is a function rather than a method because Go methods cannot have type parameters. Registration errors are reported by Run*.
Example ¶
Tools with a struct output send structured content alongside its JSON text; per-tool options set annotations, scopes and limits.
package main
import (
"context"
"time"
"go.xchunk.org/argon"
)
func main() {
type SearchInput struct {
Query string `json:"query" jsonschema:"full-text query"`
Limit int `json:"limit,omitempty" jsonschema:"maximum number of hits"`
}
type SearchOutput struct {
Hits []string `json:"hits"`
}
s := argon.New("search")
argon.Tool(s, "search", "Search the notes",
func(ctx context.Context, in SearchInput) (SearchOutput, error) {
return SearchOutput{Hits: []string{"note about " + in.Query}}, nil
},
argon.ReadOnly(),
argon.Scopes("notes:read"),
argon.ToolTimeout(5*time.Second),
)
}
Output:
Types ¶
type Annotations ¶
Annotations are behaviour hints about a tool, exposed to clients and to middleware via ToolMeta. Nil means "unspecified". Set them with ReadOnly, Destructive, Idempotent and OpenWorld.
type Content ¶
type Content interface {
// contains filtered or unexported methods
}
Content is one content block of a tool result or prompt message: TextContent, ImageContent or ResourceLink. The set is closed; it cannot be implemented outside this package.
type Handler ¶
Handler executes a tool call at the middleware level (see Middleware). A returned error becomes an isError result.
type Identity ¶
Identity is the authenticated caller. See package auth.
func IdentityFrom ¶
IdentityFrom returns the caller identity, or nil when the call is not authenticated (e.g. on stdio).
type ImageContent ¶
type ImageContent struct {
// MIMEType is the image type, e.g. "image/png".
MIMEType string
// Data holds the raw image bytes; Argon base64-encodes them on the wire.
Data []byte
}
ImageContent is an image, such as a chart or a screenshot.
type Middleware ¶
Middleware wraps a tool Handler with cross-cutting behaviour such as logging, metrics or authorization. Register it for all tools with Use or for one tool with With. It does not apply to resources and prompts.
audit := func(next argon.Handler) argon.Handler {
return func(ctx context.Context, req *argon.Request) (*argon.Result, error) {
log.Printf("tool %s called", req.Tool)
return next(ctx, req)
}
}
s := argon.New("notes", argon.Use(audit))
type Option ¶
type Option func(*Server)
Option configures a Server.
func Auth ¶
Auth enables bearer-token authentication on the HTTP transport. It has no effect on stdio.
func Instructions ¶
Instructions sets instructions sent to clients on initialization.
func LogCalls ¶
func LogCalls() Option
LogCalls logs every tool call (name, duration, error) at Info level. Arguments and results are never logged; invalid input is logged without the rejected values. Errors returned by handlers are logged as they are.
func Logger ¶
Logger sets the server logger. On stdio it must not write to stdout.
By default Argon logs to stderr at Warn level (Info when LogCalls is set). Records from the underlying SDK are always limited to Warn and above.
func Timeout ¶
Timeout sets the default per-call timeout. Zero disables it.
The timeout cancels the handler's context; a handler that ignores its context keeps running, and the call waits for it.
func Use ¶
func Use(mws ...Middleware) Option
Use adds global middleware, applied to every tool.
Example ¶
Middleware sees every tool call with the tool's metadata.
package main
import (
"context"
"log"
"go.xchunk.org/argon"
)
func main() {
audit := func(next argon.Handler) argon.Handler {
return func(ctx context.Context, req *argon.Request) (*argon.Result, error) {
if d := req.Meta.Annotations.Destructive; d != nil && *d {
log.Printf("destructive tool %s called", req.Tool)
}
return next(ctx, req)
}
}
_ = argon.New("audited", argon.Use(audit))
}
Output:
type PromptMessage ¶
PromptMessage is one message of a rendered prompt: a role and a content block. Use UserMessage and AssistantMessage for text, or set Content to any Content block such as an ImageContent.
func AssistantMessage ¶
func AssistantMessage(text string) PromptMessage
AssistantMessage returns a text message from the assistant.
func UserMessage ¶
func UserMessage(text string) PromptMessage
UserMessage returns a text message from the user.
type PromptOption ¶
type PromptOption func(*promptDef)
PromptOption configures a prompt.
func PromptMaxOutput ¶
func PromptMaxOutput(n int) PromptOption
PromptMaxOutput overrides the server default size limit for this prompt. Zero keeps the default; a negative value disables the limit.
func PromptScopes ¶
func PromptScopes(scopes ...string) PromptOption
PromptScopes requires the caller to hold all of the given scopes. Without authentication (stdio, or HTTP without Auth) requests are always rejected; see Scopes.
func PromptTimeout ¶
func PromptTimeout(d time.Duration) PromptOption
PromptTimeout overrides the server default timeout for this prompt. Zero keeps the default; a negative value disables the timeout.
type Request ¶
type Request struct {
// Tool is the name of the invoked tool.
Tool string
// Arguments are the raw JSON arguments sent by the client, before
// validation and decoding.
Arguments json.RawMessage
// Meta describes the invoked tool with its effective policies (server
// defaults applied). Middleware must treat it as read-only.
Meta *ToolMeta
}
Request is a single tool call as seen by middleware (see Middleware). Typed handlers registered with Tool never see it: they receive their decoded input instead.
type ResourceContents ¶
type ResourceContents struct {
// URI of the content; defaults to the requested URI when empty.
URI string
// MIMEType defaults to the resource's declared type (see MIMEType).
MIMEType string
// Text holds text contents; leave empty for binary contents.
Text string
// Blob holds binary contents; Argon base64-encodes them on the wire.
Blob []byte
}
ResourceContents is what a resource handler returns: text or binary data (see TextResource and BlobResource), never both. Note that empty text is sent without a text field, which strict clients may not accept; prefer a non-empty placeholder or an empty blob for empty contents.
func BlobResource ¶
func BlobResource(mimeType string, data []byte) ResourceContents
BlobResource returns binary contents of the given MIME type.
func TextResource ¶
func TextResource(text string) ResourceContents
TextResource returns text contents.
type ResourceLink ¶
ResourceLink points the client at a resource it can read separately (see Resource), instead of embedding the content.
type ResourceOption ¶
type ResourceOption func(*resourceDef)
ResourceOption configures a resource or resource template.
func MIMEType ¶
func MIMEType(m string) ResourceOption
MIMEType declares the resource's MIME type; it is listed to clients and used for contents that do not set their own.
func ResourceMaxOutput ¶
func ResourceMaxOutput(n int) ResourceOption
ResourceMaxOutput overrides the server default size limit for this resource. Zero keeps the default; a negative value disables the limit.
func ResourceScopes ¶
func ResourceScopes(scopes ...string) ResourceOption
ResourceScopes requires the caller to hold all of the given scopes. Without authentication (stdio, or HTTP without Auth) reads are always rejected; see Scopes.
func ResourceTimeout ¶
func ResourceTimeout(d time.Duration) ResourceOption
ResourceTimeout overrides the server default timeout for this resource. Zero keeps the default; a negative value disables the timeout.
func ResourceTitle ¶
func ResourceTitle(t string) ResourceOption
ResourceTitle sets a human-readable title.
type Result ¶
type Result struct {
Content []Content
// Structured is the structured output, sent as structuredContent. It is
// set for tools whose output type is a struct.
Structured any
// IsError marks a tool-level error the model can react to, as opposed to
// a protocol failure.
IsError bool
}
Result is the outcome of a tool call. Typed handlers may return a *Result to send several content blocks (see NewResult); middleware sees every call's Result.
func NewResult ¶
NewResult returns a result made of the given content blocks, e.g. text followed by an image and a resource link.
Example ¶
A tool can return several content blocks.
package main
import (
"context"
"go.xchunk.org/argon"
)
func main() {
s := argon.New("charts")
argon.Tool(s, "chart", "Draw a chart", func(ctx context.Context, _ struct{}) (*argon.Result, error) {
png := []byte{0x89, 'P', 'N', 'G'} // rendered elsewhere
return argon.NewResult(
argon.TextContent{Text: "Sales by month"},
argon.ImageContent{MIMEType: "image/png", Data: png},
argon.ResourceLink{URI: "file:///sales.csv", Name: "sales.csv"},
), nil
})
}
Output:
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is an MCP server definition: a set of tools plus policies. It is transport-independent; see Run, RunStdio and RunHTTP.
Register tools, resources and prompts before serving, from a single goroutine. The set is fixed when Run*, Handler or argontest builds the server: later registrations are not served by servers already built.
func (*Server) Handler ¶
Handler returns s as an http.Handler for embedding into an existing HTTP server. Authentication configured via Auth is applied.
The handler serves MCP on any path it receives, so it can be mounted under a prefix (mux.Handle("/mcp", h)) without http.StripPrefix. With Auth, set the Audience to the full endpoint URL (e.g. "https://example.com/mcp") and also mount ResourceMetadata at the root mux: the RFC 9728 metadata path lives outside the prefix.
Example ¶
An HTTP server protected by an OAuth authorization server, mounted under a path prefix in an existing mux.
package main
import (
"context"
"log"
"net/http"
"go.xchunk.org/argon"
"go.xchunk.org/argon/auth"
"go.xchunk.org/argon/auth/oidc"
)
func main() {
ctx := context.Background()
v, err := oidc.NewVerifier(ctx, "https://auth.example.com", "https://api.example.com/mcp")
if err != nil {
log.Fatal(err)
}
s := argon.New("notes", argon.Auth(auth.Config{
Issuer: "https://auth.example.com",
Audience: "https://api.example.com/mcp",
Verifier: v,
}))
argon.Tool(s, "whoami", "Show the caller", func(ctx context.Context, _ struct{}) (string, error) {
return argon.IdentityFrom(ctx).Subject, nil
})
h, err := s.Handler()
if err != nil {
log.Fatal(err)
}
path, meta, err := s.ResourceMetadata()
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
mux.Handle("/mcp", h)
mux.Handle(path, meta)
log.Fatal(http.ListenAndServe(":8080", mux))
}
Output:
func (*Server) ResourceMetadata ¶
ResourceMetadata returns the OAuth protected-resource metadata endpoint (RFC 9728) and the absolute path to serve it at. Only needed when Handler is mounted under a prefix; RunHTTP and root mounts serve it already. It fails when Auth is not configured.
h, _ := s.Handler()
path, meta, _ := s.ResourceMetadata()
mux.Handle("/mcp", h)
mux.Handle(path, meta)
func (*Server) Run ¶
Run serves s until SIGINT/SIGTERM. It uses stdio unless an HTTP address is given via the --http flag (--http :8080 or --http=:8080) or ARGON_HTTP.
type ToolMeta ¶
type ToolMeta struct {
Name string
Title string
Annotations Annotations
// Scopes the caller must hold (see Scopes).
Scopes []string
// Timeout and MaxOutput are the effective limits for this call; zero
// means disabled.
Timeout time.Duration
MaxOutput int
}
ToolMeta describes the invoked tool to middleware, e.g. to log it or to gate tools marked Destructive.
type ToolOption ¶
type ToolOption func(*toolDef)
ToolOption configures a single tool.
func Destructive ¶
func Destructive() ToolOption
Destructive marks the tool as possibly performing destructive updates.
func Idempotent ¶
func Idempotent() ToolOption
Idempotent marks repeated calls with the same arguments as having no extra effect.
func OpenWorld ¶
func OpenWorld() ToolOption
OpenWorld marks the tool as interacting with external entities.
func ReadOnly ¶
func ReadOnly() ToolOption
ReadOnly marks the tool as not modifying its environment.
func Scopes ¶
func Scopes(scopes ...string) ToolOption
Scopes requires the caller to hold all of the given scopes. Scopes come from the verified token, so without authentication (stdio, or HTTP without Auth) calls are always rejected.
func ToolMaxOutput ¶
func ToolMaxOutput(n int) ToolOption
ToolMaxOutput overrides the server default output limit for this tool. Zero keeps the default; a negative value disables the limit.
func ToolTimeout ¶
func ToolTimeout(d time.Duration) ToolOption
ToolTimeout overrides the server default timeout for this tool. Zero keeps the default; a negative value disables the timeout.
func With ¶
func With(mws ...Middleware) ToolOption
With adds middleware that applies to this tool only.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package argontest provides helpers for unit-testing Argon servers without spawning a process: tools are called through an in-memory MCP session.
|
Package argontest provides helpers for unit-testing Argon servers without spawning a process: tools are called through an in-memory MCP session. |
|
Package auth defines the caller identity and token verification contracts used by Argon's HTTP transport.
|
Package auth defines the caller identity and token verification contracts used by Argon's HTTP transport. |
|
oidc
Package oidc provides an issuer-driven token verifier: OIDC Discovery / RFC 8414 metadata, JWKS-backed JWT verification and RFC 7662 introspection for opaque tokens.
|
Package oidc provides an issuer-driven token verifier: OIDC Discovery / RFC 8414 metadata, JWKS-backed JWT verification and RFC 7662 introspection for opaque tokens. |
|
examples
|
|
|
auth
command
Command auth is an HTTP MCP server protected by an OAuth authorization server.
|
Command auth is an HTTP MCP server protected by an OAuth authorization server. |
|
hello
command
Command hello is the smallest useful Argon server.
|
Command hello is the smallest useful Argon server. |
|
internal
|
|
|
errs
Package errs holds the sentinel errors shared by Argon's public API and its SDK adapter, so the adapter can map them to protocol errors without importing the root package.
|
Package errs holds the sentinel errors shared by Argon's public API and its SDK adapter, so the adapter can map them to protocol errors without importing the root package. |
|
kctest
Package kctest helps integration tests talk to the Keycloak instance from test/keycloak.
|
Package kctest helps integration tests talk to the Keycloak instance from test/keycloak. |
|
sdkadapter
Package sdkadapter is the only package that imports the official MCP Go SDK.
|
Package sdkadapter is the only package that imports the official MCP Go SDK. |
|
stdioguard
Package stdioguard keeps stdout reserved for protocol messages on the stdio transport: stray writes from user code would corrupt the JSON-RPC stream.
|
Package stdioguard keeps stdout reserved for protocol messages on the stdio transport: stray writes from user code would corrupt the JSON-RPC stream. |
|
testhook
Package testhook lets argontest reach unexported server internals without widening the public API.
|
Package testhook lets argontest reach unexported server internals without widening the public API. |