mcp

package module
v0.62.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Overview

Package mcp adapts Scope tools and prompts to the Model Context Protocol (https://modelcontextprotocol.io/).

Protocol clients, servers, sessions, and transports come from the Scope-maintained SDK fork, github.com/Tangerg/go-sdk/mcp; consumers must use that module path for protocol types. Its decoder keeps exact numbers in structuredContent and distinguishes explicit null from absence.

Remote IsError results become tool.Failure values of kind tool.FailureKindFailed with every content part and structured detail; because MCP does not encode refusal, that kind does not imply execution began. Register projects the same Failure back into an IsError result. Invalid arguments stay model-visible error results, while input-validation defects, unknown local outcomes, and authorization errors become generic protocol errors, never definite results or internal diagnostics. With SDK automatic multi-round-trip disabled, a negotiated single form elicitation becomes a tool.InputRequest. The validated answer carries the remote state back through the same discovered binding; other input kinds return ErrIncompleteResult. Reconnecting requires explicit remote reconciliation. Successful structured results are validated against the output schema frozen at discovery.

Scope tools receive business input explicitly through tool.Invocation and tool.Continuation. Register does not drive tool.InputRequest checkpoints. A native MCP handler that needs user input returns SDK InputRequests and resumes from InputResponses under the multi-round-trip protocol; it must protect any RequestState it sends through the client. No context helper grants elicitation or a server session. A served call that the client asked to observe carries a progress reporter, so a Tool reports with tool.ReportProgress under any driver.

Tool results and prompts share one content codec. ContentMetadataKey carries MCP annotations, resource provenance, and presentation metadata that Core has no field for, and Core metadata, citations, and media names, IDs, and metadata that MCP has no field for travel through MCP _meta as native JSON objects. A Core media reference is an opaque handle valid only with the provider that issued it, so serving one fails with ErrMediaReference; a received resource link is always a URI. When a server declares no media type for a resource link or embedded resource, Core retains that absence; the current Core MIME field owns any later declaration. Image and audio content require a declared media type. Resource links preserve the Core media name exactly, including an empty string; MCP requires the name member even when the resource is unnamed. Empty text without metadata is omitted. Embedded resources require a URI and inline content; their URI records provenance, never a link fallback. Empty inline resources return ErrEmptyEmbeddedResource because Core cannot represent them. Malformed or unsupported content is rejected. Tool schemas preserve exact JSON numbers through SDK discovery and Core validation. Native _meta values remain json.RawMessage throughout SDK decoding and Scope projection, preserving nested numbers, null, and empty values. Consumers decode metadata into their declared types when interpreting it.

Index

Examples

Constants

View Source
const ContentMetadataKey = "mcp/content"

MCP-only facts live here so Core remains the sole owner of payload and media fields.

Variables

View Source
var (
	ErrContinuationBinding = errors.New("mcp: continuation does not match this admitted remote call")
	ErrIncompleteResult    = errors.New("mcp: remote tool result requires further input")

	ErrNilServer = errors.New("mcp: server must not be nil")

	ErrNilSession = errors.New("mcp: session must not be nil")

	ErrMediaReference = errors.New("mcp: media references cannot cross MCP")

	ErrEmptyEmbeddedResource = errors.New("mcp: empty embedded resources are unsupported")
)

Functions

func AnnotatedReadOnlyConcurrencyPolicy

func AnnotatedReadOnlyConcurrencyPolicy(_, _ string, annotations sdkmcp.ToolAnnotations, _ toolcontract.Invocation) (key string, concurrent bool)

Only the host can establish whether remote hints describe actual effects. Classification neither orders execution nor authorizes calls.

func DiscoverTools

func DiscoverTools(ctx context.Context, sources []ToolSource, config ToolDiscoveryConfig) ([]toolcontract.Tool, error)
Example
package main

import (
	"context"
	"fmt"

	"github.com/Tangerg/scope/mcp"
)

func main() {
	tools, err := mcp.DiscoverTools(context.Background(), nil, mcp.ToolDiscoveryConfig{})
	if err != nil {
		panic(err)
	}

	fmt.Println(len(tools))
}
Output:
0

func EncodeToolResult added in v0.59.0

func EncodeToolResult(output toolcontract.Output) (*sdkmcp.CallToolResult, error)

EncodeToolResult projects a validated Scope tool output onto its MCP wire response.

func PromptMessagesToChat

func PromptMessagesToChat(messages []*sdkmcp.PromptMessage) ([]chat.Message, error)

Core cannot represent an empty text part, so empty MCP messages are omitted.

func Register

func Register(server *sdkmcp.Server, tools ...toolcontract.Binding) error

Atomic admission prevents partially registered catalogs. Handlers retain the admitted identities because Tools may mutate after registration.

Types

type PublicToolNameFunc

type PublicToolNameFunc func(sourceName, remoteName string) string

The Host owns collision resolution across independent server catalogs.

type RequestMetaFunc

type RequestMetaFunc func(ctx context.Context, invocation toolcontract.Invocation) sdkmcp.Meta

RequestMetaFunc derives the MCP _meta sent with one remote call from that call. Host identity such as a user is bound into the function when the tools are discovered for that user, never read back from the context.

type ToolConcurrencyPolicy

type ToolConcurrencyPolicy func(
	sourceName, remoteName string,
	annotations sdkmcp.ToolAnnotations,
	invocation toolcontract.Invocation,
) (key string, concurrent bool)

Schedulers may rerun this callback during durable recovery and retain it beyond RPC sessions. It must be deterministic, side-effect-free, safe for concurrent use, and free of Tool, session, or execution-backend captures. Annotations are isolated and the invocation is schema-validated. Results follow github.com/Tangerg/scope/agent/interaction.ConcurrentTool; direct Tool.Call invocations remain the host's responsibility.

type ToolDiscoveryConfig

type ToolDiscoveryConfig struct {
	EffectPolicy ToolEffectPolicy
	// Each source and remote name is a separate escaped path segment. An
	// explicit override must remain unique; model aliasing belongs to the
	// binding that exposes this tool to a particular model.
	PublicName PublicToolNameFunc

	// If nil, no additional request metadata is forwarded to tool calls.
	RequestMeta RequestMetaFunc

	// If nil, tools provide no overlap declaration; this does not serialize calls.
	// Protocol descriptors cannot establish resource conflicts for the host.
	ConcurrencyPolicy ToolConcurrencyPolicy
}

type ToolEffectPolicy added in v0.60.0

type ToolEffectPolicy func(sourceName, remoteName string, annotations sdkmcp.ToolAnnotations) toolcontract.Effect

ToolEffectPolicy establishes a host-trusted replay contract. MCP annotations alone are untrusted hints; IdempotentHint is not durable key deduplication. This callback runs once during discovery and must not depend on mutable state.

type ToolSource

type ToolSource struct {
	Name string

	// Discovered tools borrow this initialized session. The caller must keep it
	// open for their calls and remains responsible for closing it.
	Session *sdkmcp.ClientSession
}

Directories

Path Synopsis
internal
elicitation
Package elicitation names the MCP form-elicitation vocabulary that the pinned SDK leaves as bare strings.
Package elicitation names the MCP form-elicitation vocabulary that the pinned SDK leaves as bare strings.
managed module

Jump to

Keyboard shortcuts

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