argon

package module
v0.1.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 27 Imported by: 1 module, 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.

README

argon

CI Go Reference Release

MCP framework for Go: build Model Context Protocol servers in a few lines.

Argon is a thin, opinionated layer over the official Go SDK. The SDK owns the protocol; Argon owns ergonomics, safe defaults and token verification. SDK types never appear in Argon's API.

Status: v0.1.0 Release Candidate 1 (v0.1.0-rc.1). The v0.1 API is frozen; it may still change before v1.0.0. See CHANGELOG.md.

go get go.xchunk.org/argon

Quick start

package main

import (
	"context"
	"log"

	"go.xchunk.org/argon"
)

type GreetInput struct {
	Name string `json:"name" jsonschema:"who to greet"`
}

func main() {
	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)
	}
}

Run serves over stdio by default; pass --http 127.0.0.1:8080 (or set ARGON_HTTP=127.0.0.1:8080) for Streamable HTTP. Without Auth, listen on loopback only: :8080 exposes every tool to the network, and Argon logs a warning when it does. RunStdio, RunHTTP and Handler (an http.Handler to mount in your own server) are also available.

Tools

  • The input is a struct (or a pointer to one, or a map); its JSON Schema is inferred from json and jsonschema struct tags. Arguments are validated before your handler runs; invalid input becomes an error result the model can correct.
  • Return a string, a struct or pointer to a struct (sent as structured content with an output schema, plus its JSON as text), any other JSON-serializable value (sent as JSON text), or a *argon.Result for several blocks: argon.NewResult(argon.TextContent{...}, argon.ImageContent{...}, argon.ResourceLink{...}).
  • A returned error becomes an isError result, not a protocol failure.
  • Options: ReadOnly(), Destructive(), Idempotent(), OpenWorld(), Title(..), Scopes(..), ToolTimeout(..), ToolMaxOutput(..), With(middleware...).

Resources

Expose read-only data by URI. A fixed resource:

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"))

A family of resources from an RFC 6570 URI template. Template variables decode into a struct, converted to the field types and validated like tool input; a URI that does not decode reads as "not found":

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
	})
  • Return argon.TextResource(..) or argon.BlobResource(mime, data); the content URI defaults to the requested URI.
  • Options: MIMEType, ResourceTitle, ResourceScopes, ResourceTimeout, ResourceMaxOutput.
  • Resources share the tools' safe defaults (timeout, size limit, panic recovery). Tool middleware does not apply to them.
  • Reads made by an authenticated caller are marked cacheScope: private.
  • Test with argontest.ReadResource(t, s, uri).

Prompts

Offer reusable prompt templates. Arguments are the fields of a struct: names 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 and validated before your handler runs:

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
	}, argon.PromptTitle("Code review"))
  • Messages: argon.UserMessage(..), argon.AssistantMessage(..), or argon.PromptMessage{Role: argon.RoleUser, Content: argon.ImageContent{..}} with any content block. Use struct{} for a prompt without arguments.
  • Missing, unknown or malformed arguments are rejected with "invalid params"; handlers can reject input themselves with argon.ErrInvalidArguments.
  • Options: PromptTitle, PromptScopes, PromptTimeout, PromptMaxOutput. Prompts share the tools' safe defaults; tool middleware does not apply.
  • Test with argontest.GetPrompt(t, s, name, args).

Safe defaults

Default Value Override
Per-call timeout (tools, resources, prompts; cancels the handler's context) 60s argon.Timeout(d), argon.ToolTimeout(d)
Result size limit 1 MiB (oversized → error, never truncated) argon.MaxOutput(n), argon.ToolMaxOutput(n)
Panic recovery panics become error results, stack goes to logs —
stdout protection (stdio) fd 1 redirected to stderr; protocol uses a private copy —
Graceful stdio shutdown requests received before stdin EOF are answered —
Logging stderr, Warn and above; SDK chatter hidden argon.Logger(l), argon.LogCalls()
HTTP sessions idle sessions expire after 30 min; request bodies limited by the SDK —
HTTP connections idle keep-alive closed after 2 min; open streams end on shutdown —

Server-wide limits are disabled with zero; per-item options (ToolTimeout, ResourceMaxOutput, ...) keep the server default on zero and disable the limit with a negative value. Timeouts are cooperative: a handler that ignores its context keeps the call waiting.

Middleware (argon.Use(...) globally, argon.With(...) per tool) sees Request.Meta with the tool's name, annotations, scopes and effective limits.

Authentication (HTTP)

Argon is an OAuth 2.1 resource server: it verifies tokens, it never issues them. Run your own authorization server (Keycloak, Auth0, Authelia, Entra, …) and point Argon at it:

v, err := oidc.NewVerifier(ctx, "https://auth.example.com", "https://mcp.example.com")
if err != nil {
	log.Fatal(err)
}
s := argon.New("notes", argon.Auth(auth.Config{
	Issuer:   "https://auth.example.com",
	Audience: "https://mcp.example.com",
	Verifier: v,
}))
argon.Tool(s, "add_note", "Save a note", addNote, argon.Scopes("notes:write"))
  • auth/oidc discovers the issuer (OIDC, then RFC 8414), caches its JWKS (rate-limited refresh on unknown kid), verifies JWT signature, iss, aud, exp and nbf, and optionally introspects opaque tokens (RFC 7662, oidc.Introspection(id, secret)). Only asymmetric algorithms are accepted; none and HMAC never are.

  • The audience is mandatory, so tokens minted for other resources are rejected.

  • Unauthenticated requests get 401 with a WWW-Authenticate header pointing at the RFC 9728 metadata: /.well-known/oauth-protected-resource followed by the audience path (e.g. .../oauth-protected-resource/mcp for https://example.com/mcp).

  • Mounting under a prefix: set Audience to the full endpoint URL and also mount the metadata endpoint at the root, since its RFC 9728 path lives outside the prefix:

    h, _ := s.Handler()                     // Audience: "https://example.com/mcp"
    path, meta, _ := s.ResourceMetadata()   // "/.well-known/oauth-protected-resource/mcp"
    mux.Handle("/mcp", h)
    mux.Handle(path, meta)
    
  • auth.Static(token, identity) covers simple self-hosted setups.

  • Handlers read the caller with argon.IdentityFrom(ctx).

  • Scopes fail closed: without authentication (stdio, or HTTP without Auth) items with Scopes/ResourceScopes/PromptScopes reject every call, and Argon logs a warning naming them at startup.

  • auth/oidc is a separate package: stdio-only servers do not pull in JOSE.

Authorization servers tested end to end: Keycloak 26 (JWT and introspection; see test/keycloak and examples/auth). Reports for other servers are welcome.

Keycloak note: recent versions only let a client introspect tokens whose audience includes that client. When using oidc.Introspection, add an audience mapper for your server's client (see test/keycloak/realm-argon.json).

stdio servers have no OAuth: they run as the user, and credentials for downstream services come from the environment.

Testing

func TestGreet(t *testing.T) {
	got, err := argontest.Call[string](t, newServer(), "greet", GreetInput{Name: "Ann"})
	// ...
}
  • argontest.Call / CallResult run the tool through a real in-memory MCP session — no subprocess, no network.
  • argontest.WithIdentity(...) runs a call as a given caller, for testing Scopes and IdentityFrom.
  • argontest.NewFakeIssuer(t) is an in-process authorization server (discovery, JWKS, introspection) that mints tokens for auth tests.
Integration tests

Real-server tests carry the integration build tag and skip when the server is not running:

docker compose -f test/keycloak/compose.yaml up -d --wait
go test -tags integration ./...
docker compose -f test/keycloak/compose.yaml down

Designing tools safely

Prefer narrow, purpose-built tools — fixed commands, validated arguments, aliases instead of raw IDs — over generic ones like "run any shell command".

Be careful when one session combines tools that read untrusted content (web pages, files, email) with tools that have real side effects (messaging, file writes, shell). Content read by the first kind can steer the model into misusing the second. Mark side-effecting tools Destructive(), gate them with scopes, and keep such combinations out of one server where you can.

Known limitations (v0.1)

  • Content blocks: text, images and resource links; no audio or embedded resources yet.
  • A missing scope is reported as a tool error, not as HTTP 403 with insufficient_scope, and tools/list is not filtered by scope.
  • Streamable HTTP options (stateless mode, stream resumption, custom session timeout) are not exposed yet.

Layout

See docs/architecture.md.

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)
	}
}

Index

Examples

Constants

View Source
const (
	DefaultTimeout   = 60 * time.Second
	DefaultMaxOutput = 1 << 20 // 1 MiB
)

Safe defaults applied when not overridden.

View Source
const EnvHTTP = "ARGON_HTTP"

EnvHTTP selects the HTTP transport when set to a listen address.

Variables

View Source
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.

View Source
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"))
}

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"))
}

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"))
}

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),
	)
}

Types

type Annotations

type Annotations struct {
	ReadOnly    *bool
	Destructive *bool
	Idempotent  *bool
	OpenWorld   *bool
}

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

type Handler func(ctx context.Context, req *Request) (*Result, error)

Handler executes a tool call at the middleware level (see Middleware). A returned error becomes an isError result.

type Identity

type Identity = auth.Identity

Identity is the authenticated caller. See package auth.

func IdentityFrom

func IdentityFrom(ctx context.Context) *Identity

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

type Middleware func(Handler) Handler

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

func Auth(cfg auth.Config) Option

Auth enables bearer-token authentication on the HTTP transport. It has no effect on stdio.

func Instructions

func Instructions(text string) Option

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

func Logger(l *slog.Logger) Option

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 MaxOutput

func MaxOutput(n int) Option

MaxOutput sets the default result size limit in bytes. Zero disables it.

func Timeout

func Timeout(d time.Duration) Option

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))
}

func Version

func Version(v string) Option

Version sets the server version reported to clients.

type PromptMessage

type PromptMessage struct {
	Role    Role
	Content Content
}

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.

func PromptTitle

func PromptTitle(t string) PromptOption

PromptTitle sets a human-readable title.

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 struct {
	URI         string
	Name        string
	Title       string
	Description string
	MIMEType    string
}

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 Image

func Image(mimeType string, data []byte) *Result

Image returns a result consisting of a single image.

func NewResult

func NewResult(blocks ...Content) *Result

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
	})
}

func Text

func Text(s string) *Result

Text returns a result consisting of a single text block.

type Role

type Role string

Role is the speaker of a prompt message.

const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
)

Prompt message roles.

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 New

func New(name string, opts ...Option) *Server

New creates a server named name.

func (*Server) Err

func (s *Server) Err() error

Err reports registration errors accumulated so far.

func (*Server) Handler

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

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))
}

func (*Server) ResourceMetadata

func (s *Server) ResourceMetadata() (path string, h http.Handler, err error)

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

func (s *Server) Run() error

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.

func (*Server) RunHTTP

func (s *Server) RunHTTP(ctx context.Context, addr string) error

RunHTTP serves s over Streamable HTTP on addr until ctx is done.

On shutdown it stops accepting connections, ends open server-to-client streams (GET requests) and waits up to 5s for in-flight requests before closing the remaining connections.

func (*Server) RunStdio

func (s *Server) RunStdio(ctx context.Context) error

RunStdio serves s over stdin/stdout. While it runs, stdout is redirected to stderr (at the file-descriptor level on Unix) so stray writes cannot corrupt the protocol stream.

type TextContent

type TextContent struct {
	Text string
}

TextContent is a plain-text block.

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 Title

func Title(t string) ToolOption

Title sets a human-readable title.

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.

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.

Jump to

Keyboard shortcuts

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