mcp

package
v0.82.1 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: Apache-2.0 Imports: 49 Imported by: 0

Documentation

Overview

Package mcp implements a Model Context Protocol (MCP) server for Dingo.

It enables Large Language Models (LLMs) and AI agents (e.g. Claude Desktop, Cursor, Cline) to query Dingo's SQLite metadata store and inspect live Cardano blockchain state directly.

The server exposes:

  • Read-only SQLite query tools (sqlite_query, sqlite_table_schema, sqlite_explain)
  • Granular Cardano domain tools (get_cardano_tip, get_block, get_transaction, get_utxos, get_account, get_epoch_summary, get_pool_performance, get_asset_info, get_utxos_by_asset, get_governance_state, resolve_datum_or_script, evaluate_tx, get_node_info, get_protocol_parameters, get_mempool_info, decode_address, get_governance_proposal, calculate_min_utxo)
  • Passive context resources (dingo://node/status, dingo://schema/tables, dingo://schema/table/<name>, dingo://dbsync/cheatsheet, dingo://docs/...)
  • Official agent workflows via MCP prompts (diagnose_node_health, simulate_and_diagnose_tx, audit_pool_rewards, track_asset_portfolio, conway_governance_brief, investigate_address)
  • Transport support for Streamable HTTP (/mcp) and Server-Sent Events (/sse)
  • Security middleware with token-bucket rate limiting, optional Bearer auth, and input/output sanitization against prompt injection attacks.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatCell

func FormatCell(val any) string

FormatCell formats a single database column value for LLM consumption, summarizing large binary blobs or hex strings so they do not exhaust the client's context window.

func FormatMarkdownTable

func FormatMarkdownTable(columns []string, rows [][]string) string

FormatMarkdownTable converts columns and row records into a clean GitHub Markdown table.

func NewMCPServer

func NewMCPServer(
	ctx context.Context,
	cfg ProviderConfig,
	deps ProviderDependencies,
) (*mcp.Server, *sql.DB, error)

NewMCPServer constructs and initializes an MCP Server with all Cardano and SQLite tools and resources, using ctx for startup work.

func OpenReadOnlySQLite

func OpenReadOnlySQLite(
	ctx context.Context,
	databasePath string,
) (*sql.DB, error)

OpenReadOnlySQLite opens a read-only SQLite connection pool with busy timeout and query_only pragma, using ctx for the initial connection.

func RegisterCardanoTools

func RegisterCardanoTools(
	server *mcp.Server,
	db *sql.DB,
	ls *ledger.LedgerState,
	mp mempool.Service,
	network string,
	queryTimeout time.Duration,
	addressLookups ...utxoAddressLookup,
)

RegisterCardanoTools registers domain-specific Cardano and db-sync aligned tools.

func RegisterPrompts

func RegisterPrompts(
	server *mcp.Server,
	_ *sql.DB,
	_ *ledger.LedgerState,
	_ string,
)

RegisterPrompts registers standard, pre-engineered agent workflows with the MCP server.

func RegisterProvider

func RegisterProvider(host *plugin.Host) error

RegisterProvider registers the built-in MCP provider with the plugin host.

func RegisterResources

func RegisterResources(
	server *mcp.Server,
	db *sql.DB,
	ls *ledger.LedgerState,
	network string,
	timeouts ...time.Duration,
)

RegisterResources registers passive MCP resources for schema exploration and db-sync guidance. Registration problems are logged through slog.Default.

func RegisterSQLiteTools

func RegisterSQLiteTools(
	server *mcp.Server,
	db *sql.DB,
	queryTimeout time.Duration,
	maxRows int,
)

RegisterSQLiteTools registers the SQLite inspection and querying tools with the MCP server.

func SanitizeExternalString

func SanitizeExternalString(input string) string

SanitizeExternalString cleans an external or user-provided string by stripping invisible Unicode formatting characters, bidirectional overrides, and control characters that are commonly exploited in prompt injection or terminal manipulation attacks.

func SecurityMiddleware

func SecurityMiddleware(
	authToken string,
	reqPerSec float64,
	burst int,
	allowedOrigins []string,
	next http.Handler,
) http.Handler

SecurityMiddleware wraps an HTTP handler with optional authentication, rate limiting, and CORS.

func ValidateReadOnlyQuery

func ValidateReadOnlyQuery(query string) error

ValidateReadOnlyQuery accepts one read-only SQLite statement. SQLite still checks syntax; the connection's mode=ro and query_only enforce the final boundary.

func WrapUntrustedChainData

func WrapUntrustedChainData(data string) string

WrapUntrustedChainData encapsulates user-supplied on-chain strings (e.g. metadata text, datum representations, anchor descriptions) in explicit delimiters to alert LLMs that the contents are untrusted raw data rather than system directives.

Types

type AccountParams

type AccountParams struct {
	StakeAddressOrCredential string `` /* 129-byte string literal not displayed */
	CredentialType           string `` /* 220-byte string literal not displayed */
}

AccountParams defines the input schema for get_account.

type AssetInfoParams

type AssetInfoParams struct {
	PolicyID  string `json:"policy_id"            jsonschema:"Hex-encoded 28-byte (56 hex characters) minting policy ID"`
	AssetName string `` /* 135-byte string literal not displayed */
}

AssetInfoParams defines the input schema for get_asset_info.

type BlockParams

type BlockParams struct {
	HashOrSlot string `json:"hash_or_slot" jsonschema:"Hex-encoded block hash (64 chars) or decimal slot number"`
}

BlockParams defines the input schema for get_block.

type CalculateMinUtxoParams

type CalculateMinUtxoParams struct {
	OutputCBORHex  string  `` /* 203-byte string literal not displayed */
	Address        string  `` /* 156-byte string literal not displayed */
	CoinsPerByte   *uint64 `` /* 141-byte string literal not displayed */
	HasDatum       bool    `json:"has_datum,omitempty"           jsonschema:"Whether the output includes a 32-byte datum hash."`
	InlineDatumHex string  `json:"inline_datum_hex,omitempty"    jsonschema:"Optional hex-encoded CBOR of an inline datum attached to the output."`
	RefScriptHex   string  `json:"ref_script_hex,omitempty"      jsonschema:"Optional hex-encoded reference script attached to the output."`
	AssetsCount    int     `json:"assets_count,omitempty"        jsonschema:"Total number of distinct native asset entries in the multi-asset value."`
	PoliciesCount  int     `` /* 143-byte string literal not displayed */
}

CalculateMinUtxoParams defines input schema for calculate_min_utxo.

type DecodeAddressParams

type DecodeAddressParams struct {
	Address string `json:"address" jsonschema:"Cardano address in Bech32 (addr..., addr_test..., stake...) or Byron base58 format."`
}

DecodeAddressParams defines input schema for decode_address.

type EpochSummaryParams

type EpochSummaryParams struct {
	Epoch *int `json:"epoch,omitempty" jsonschema:"Epoch number (optional, defaults to current epoch)"`
}

EpochSummaryParams defines the input schema for get_epoch_summary.

type EvaluateTxParams

type EvaluateTxParams struct {
	Cbor string `json:"cbor" jsonschema:"Hex-encoded or base64-encoded raw transaction CBOR"`
}

EvaluateTxParams defines the input schema for evaluate_tx.

type GovernanceProposalParams

type GovernanceProposalParams struct {
	TxHash      string  `json:"tx_hash,omitempty"      jsonschema:"Optional 64-character hex transaction hash of the governance proposal."`
	ActionIndex *uint32 `json:"action_index,omitempty" jsonschema:"Optional governance action index within the transaction (default 0)."`
	Status      string  `` /* 142-byte string literal not displayed */
	Limit       int     `json:"limit,omitempty"        jsonschema:"Maximum number of proposals to return when listing (default 10, max 50)."`
}

GovernanceProposalParams defines input schema for get_governance_proposal.

type GovernanceStateParams

type GovernanceStateParams struct {
	DrepCredential string `json:"drep_credential,omitempty" jsonschema:"Optional hex credential or Bech32 DRep ID (drep1...) to inspect a specific DRep"`
}

GovernanceStateParams defines the input schema for get_governance_state.

type MempoolInfoParams

type MempoolInfoParams struct {
	TxHash string `json:"tx_hash,omitempty" jsonschema:"Optional 64-character hex transaction hash to inspect in the mempool."`
	Limit  int    `` /* 130-byte string literal not displayed */
}

MempoolInfoParams defines input schema for get_mempool_info.

type NodeInfoParams

type NodeInfoParams struct {
	Topic string `` /* 251-byte string literal not displayed */
}

NodeInfoParams defines the input schema for get_node_info.

type PoolPerformanceParams

type PoolPerformanceParams struct {
	PoolID string `json:"pool_id"         jsonschema:"Bech32 pool ID (e.g. pool1...) or hex pool key hash (56 hex characters)"`
	Epoch  *int   `json:"epoch,omitempty" jsonschema:"Specific epoch number to inspect (optional, defaults to last 10 epochs)"`
	Limit  int    `json:"limit,omitempty" jsonschema:"Maximum epochs of history to return (default 10, max 50)"`
}

PoolPerformanceParams defines the input schema for get_pool_performance.

type ProtocolParametersParams

type ProtocolParametersParams struct {
	Epoch *uint64 `json:"epoch,omitempty" jsonschema:"Historical epoch requests are unsupported. Omit to query current active parameters."`
}

ProtocolParametersParams defines input schema for get_protocol_parameters.

type ProviderConfig

type ProviderConfig struct {
	Port         uint                `yaml:"port"`
	Host         string              `yaml:"host"`
	AuthToken    string              `yaml:"authToken"`
	RateLimit    float64             `yaml:"rateLimit"` // requests per second (0 = unlimited)
	Burst        int                 `yaml:"burst"`     // rate limiter burst allowance (default 15)
	QueryTimeout time.Duration       `yaml:"queryTimeout"`
	MaxRows      int                 `yaml:"maxRows"`
	TLS          apiconfig.TLSPolicy `yaml:"tls"`
}

ProviderConfig holds the configuration for the MCP API server.

func DefaultProviderConfig

func DefaultProviderConfig() ProviderConfig

DefaultProviderConfig returns default settings for the MCP server.

type ProviderDependencies

type ProviderDependencies struct {
	Logger             *slog.Logger
	Database           *database.Database
	SQLDB              *sql.DB // optional SQLite pool; arbitrary queries borrow read-only connections
	LedgerState        *ledger.LedgerState
	Mempool            mempool.Service
	Host               string
	Network            string
	CORSAllowedOrigins []string
}

ProviderDependencies contains the dependencies injected by the Node coordinator.

type ResolveHashParams

type ResolveHashParams struct {
	Hash string `json:"hash" jsonschema:"Hex-encoded datum hash (32 bytes / 64 hex characters) or script hash (28 bytes / 56 hex characters)"`
}

ResolveHashParams defines the input schema for resolve_datum_or_script.

type SQLiteExplainParams

type SQLiteExplainParams struct {
	Query string `json:"query" jsonschema:"The SQL query to explain using EXPLAIN QUERY PLAN"`
}

SQLiteExplainParams defines the input schema for sqlite_explain.

type SQLiteQueryParams

type SQLiteQueryParams struct {
	Query  string `json:"query"            jsonschema:"The SQL SELECT query to execute against Dingo's SQLite database"`
	Limit  int    `json:"limit,omitempty"  jsonschema:"Maximum rows to return (default 50, capped by configured maxRows and 200)"`
	Offset int    `json:"offset,omitempty" jsonschema:"Number of rows to skip for pagination (default 0)"`
}

SQLiteQueryParams defines the input schema for sqlite_query.

type SQLiteTableSchemaParams

type SQLiteTableSchemaParams struct {
	TableName string `json:"table_name" jsonschema:"Name of the SQLite table to inspect"`
}

SQLiteTableSchemaParams defines the input schema for sqlite_table_schema.

type Server

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

Server encapsulates the MCP HTTP and SSE transport server.

func NewServer

func NewServer(
	ctx context.Context,
	cfg ProviderConfig,
	deps ProviderDependencies,
	resolvedTLS apiconfig.EffectiveTLS,
	listenAddress string,
) (*Server, error)

NewServer creates a new MCP Server instance.

func (*Server) Start

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

Start binds the socket and starts serving in a background goroutine.

func (*Server) Stop

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

Stop gracefully shuts down the server.

type TipParams

type TipParams struct{}

TipParams defines the input schema for get_cardano_tip.

type TransactionParams

type TransactionParams struct {
	TxHash string `json:"tx_hash" jsonschema:"Hex-encoded 64-character transaction hash"`
}

TransactionParams defines the input schema for get_transaction.

type UTxOsParams

type UTxOsParams struct {
	AddressOrCredential string `json:"address_or_credential" jsonschema:"Bech32 Cardano address or hex payment credential"`
	Limit               int    `json:"limit,omitempty"       jsonschema:"Maximum UTxOs to return (default 20, max 100)"`
	Offset              int    `json:"offset,omitempty"      jsonschema:"Offset for raw-credential searches only; full addresses use cursor"`
	Cursor              string `json:"cursor,omitempty"      jsonschema:"Continuation cursor from a full-address query"`
}

UTxOsParams defines the input schema for get_utxos.

type UtxosByAssetParams

type UtxosByAssetParams struct {
	PolicyID  string `json:"policy_id"            jsonschema:"Hex-encoded 28-byte (56 hex characters) minting policy ID"`
	AssetName string `` /* 135-byte string literal not displayed */
	Limit     int    `json:"limit,omitempty"      jsonschema:"Maximum UTxOs to return (default 50, max 200)"`
	Offset    int    `json:"offset,omitempty"     jsonschema:"Pagination offset (default 0)"`
}

UtxosByAssetParams defines the input schema for get_utxos_by_asset.

Jump to

Keyboard shortcuts

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