scriptsession

package
v1.164.0 Latest Latest
Warning

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

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

Documentation

Overview

Package scriptsession is the production Caller a managed script's run issues its platform calls through: one in-memory MCP session against the fully assembled server, and the reading of a failed result as the refusal the engine paces on (#1419). Extracted from internal/platform/scriptrun so the engine holds the interpreter and its bindings, and the session plumbing is visibly a second thing.

Index

Constants

View Source
const (
	AppDBQuery   = "appdb.query"
	AppDBExecute = "appdb.execute"
	// AppDBBatch is platform.batch: statements pipelined in one transaction
	// that commits when every one succeeded (#2402).
	AppDBBatch = "appdb.batch"
	// The calls platform.transaction makes (#2402): open the transaction,
	// run statements in it, and end it. Each statement goes through the same
	// call path as platform.query's, so a draft refuses a write inside a
	// transaction and a recording keeps each statement and how it ended.
	AppDBBegin     = "appdb.begin"
	AppDBTxQuery   = "appdb.tx_query"
	AppDBTxExecute = "appdb.tx_execute"
	AppDBTxBatch   = "appdb.tx_batch"
	AppDBCommit    = "appdb.commit"
	AppDBRollback  = "appdb.rollback"
	// The calls tx.savepoint makes (#2452): open a savepoint in the
	// transaction, then release it or roll back to it.
	AppDBSavepoint  = "appdb.savepoint"
	AppDBRelease    = "appdb.release"
	AppDBRollbackTo = "appdb.rollback_to"
	// The calls query_iter makes (#2454): declare a cursor over a query, in
	// the run's transaction or a READ ONLY one of its own, read it a page at
	// a time, and close it.
	AppDBCursorOpen  = "appdb.cursor_open"
	AppDBCursorFetch = "appdb.cursor_fetch"
	AppDBCursorClose = "appdb.cursor_close"
	// The calls copy_in and copy_out make (#2453). Their rows and copied
	// bytes never reach a recording (RecordedArgs, RecordedOut).
	AppDBCopyIn  = "appdb.copy_in"
	AppDBCopyOut = "appdb.copy_out"
	// AppDBMaintain is platform.maintain (#2410): ANALYZE, VACUUM or REINDEX
	// outside a transaction, for an administrator or a persona the
	// connection's schema_apply_personas names.
	AppDBMaintain = "appdb.maintain"
)

The calls a script's platform.query and platform.execute make on an application database (#2428). They are answered by the session caller itself, against the connection's pool, and never reach the MCP server: an application's request path runs many statements and cannot pay a tool call, the middleware chain and an audit row for each. They go through the host's call path all the same, so the draft write barrier classifies them, a recording keeps them and a script test answers them from the recording.

View Source
const CodeSchemaOfAnotherApplication = "schema_of_another_application"

CodeSchemaOfAnotherApplication is a statement refused on a schema another application holds (#2539).

View Source
const MaxResourceReadBytes = 8 << 20

MaxResourceReadBytes is the most one read hands a script: its bytes cross the session base64-encoded, a third larger, inside the transport's 16 MiB frame (mcp.DefaultMaxLineLength).

View Source
const ResourceRead = "resource.read"

ResourceRead is platform.read_resource as the session answers it (#2616): a managed resource's bytes and their sha256, for a script that used to read them straight from the platform's bucket. It is a host call, not a tool, and a recording keeps it like any other, so a test replays the bytes the run read.

View Source
const TextResultKey = "text"

TextResultKey is the single field a tool result arrives under when the tool returned no structured object: the text it produced, verbatim (SessionCaller.CallTool).

Variables

This section is empty.

Functions

func InstallAppDB added in v1.153.0

func InstallAppDB(a AppDB)

InstallAppDB sets the application-database runner every script session opened after it uses.

func InstallAppDBHandlers added in v1.161.0

func InstallAppDBHandlers(h AppDBHandlers)

InstallAppDBHandlers sets the tool-call handlers every script session's application database statements are put through.

func IsAppDB added in v1.153.0

func IsAppDB(connection string) bool

IsAppDB reports whether connection names an application database, which is how platform.query and platform.execute choose between the direct path and the query engine's tools. A connection another replica saved a moment ago is one (#2662).

func IsAppDBCall added in v1.153.0

func IsAppDBCall(name string) bool

IsAppDBCall reports whether name is one of the calls a session answers against an application database rather than the MCP server.

func RecordedArgs added in v1.153.0

func RecordedArgs(tool string, args map[string]any) map[string]any

RecordedArgs is a call's arguments as a recording keeps and matches them: a copy_in's rows are bound values, kept nowhere but the database, so they are replaced by their count (#2453), and a password a SQL string gives a role is replaced by a placeholder (#2475).

func RecordedOut added in v1.153.0

func RecordedOut(tool string, out map[string]any) map[string]any

RecordedOut is a call's answer as a recording keeps it: a copy_out's bytes are an output, written where outputs go, never into a recording.

func WithEndpoint added in v1.153.0

func WithEndpoint(ctx context.Context, caller EndpointCaller) context.Context

WithEndpoint marks ctx as an endpoint request's session, carrying its caller: a session opened on it sets mcp.user_id and mcp.email from caller, never from the script's author. A public endpoint's caller is the zero value.

func WithRunAs added in v1.154.2

func WithRunAs(ctx context.Context, app, connection string) context.Context

WithRunAs records on ctx the application the session's script is a part of and the connection its schema is on ("" for none), for a caller that read them already: an endpoint request reads them with its stamp, so none of its statements queries for them.

func WithScript added in v1.154.2

func WithScript(ctx context.Context, scriptID string) context.Context

WithScript marks ctx as a session of the script with id scriptID: a draft, which carries no producer, names its script this way. "" leaves ctx as it is.

Types

type AppDB added in v1.153.0

type AppDB struct {
	// Runner returns the live runner, or nil on a deployment with none.
	Runner func() AppDBRunner
	// Authorize refuses a connection the identity on ctx may not use, and
	// names the persona it was allowed as, which chooses the database login
	// role its statements run as (#2403). ctx is the session's own, which
	// carries the run's identity.
	Authorize func(ctx context.Context, connection string) (persona string, err error)
	// TestDatabase builds a script test's throwaway database for a
	// connection from its migrations in schemas, every schema when empty
	// (#2407), and returns its runner and the function that drops it. Nil
	// on a deployment that keeps no migrations.
	TestDatabase func(ctx context.Context, connection string, schemas []string) (AppDBRunner, func(), error)
	// AdminPersona is the persona that is the platform's administrator,
	// which platform.maintain is allowed for on every connection.
	AdminPersona string
	// Applications answers which application's run role a script's
	// statements log in as, and which application holds a schema (#2539);
	// its zero value answers none.
	Applications Applications
}

AppDB is what the platform installs for the script sessions it opens.

type AppDBCursor added in v1.153.0

type AppDBCursor interface {
	Next(ctx context.Context) (*postgres.Result, bool, error)
	Close()
}

AppDBCursor is one query read in pages: a *postgres.Cursor.

type AppDBHandlers added in v1.161.0

type AppDBHandlers interface {
	// Statement is what the handlers on its connection make of a statement:
	// an error the run is refused with, or the transformer its rows pass
	// through (nil for none).
	Statement(ctx context.Context, st callhandler.Statement) (calltransform.Transformer, error)
}

AppDBHandlers puts a script's statement on an application database through the tool-call handlers (#2436, #2634): that path binds straight to a pool and never crosses the tools/call chain, so the handlers are asked here. A policy decides the statement; a transform covering the run changes the rows it returns, and refuses a statement using a column it protects.

type AppDBRunner added in v1.153.0

type AppDBRunner interface {
	// ServesConnection reports whether name is an application database
	// connection, one another replica just saved included (#2662).
	ServesConnection(ctx context.Context, name string) bool
	Query(ctx context.Context, s postgres.Statement) (*postgres.Result, error)
	Execute(ctx context.Context, s postgres.Statement) (*postgres.Result, error)
	Batch(ctx context.Context, connection string, stmts []postgres.Statement) ([]*postgres.Result, error)
	Begin(ctx context.Context, o postgres.TxOptions) (AppDBTx, error)
	OpenCursor(ctx context.Context, s postgres.Statement, pageRows int) (AppDBCursor, error)
	CopyIn(ctx context.Context, in postgres.CopyIn) (int64, error)
	CopyOut(ctx context.Context, s postgres.Statement, format string, w io.Writer, maxBytes int64) (*postgres.CopyOutResult, error)
	RunMaintenance(ctx context.Context, connection, stmt string, lockTimeout, timeout time.Duration) error
	ApplyPersonas(connection string) []string
}

AppDBRunner runs statements on application databases: the postgres toolkit.

type AppDBTx added in v1.153.0

type AppDBTx interface {
	Connection() string
	Query(ctx context.Context, s postgres.Statement) (*postgres.Result, error)
	Execute(ctx context.Context, s postgres.Statement) (*postgres.Result, error)
	Batch(ctx context.Context, stmts []postgres.Statement) ([]*postgres.Result, error)
	Commit(ctx context.Context) error
	Rollback()
	Savepoint(ctx context.Context) (string, error)
	Release(ctx context.Context, name string) error
	RollbackTo(ctx context.Context, name string) error
	OpenCursor(ctx context.Context, s postgres.Statement, pageRows int) (AppDBCursor, error)
	CopyIn(ctx context.Context, in postgres.CopyIn) (int64, error)
}

AppDBTx is one transaction a script holds: a *postgres.Tx.

type Applications added in v1.154.2

type Applications struct {
	// RunAs is the id of the application whose run role the statements of
	// the script scriptID runs on connection log in as: the application it
	// is a part of, when that application holds a schema on connection. ""
	// for none.
	RunAs func(ctx context.Context, scriptID, connection string) string
	// Holder is the id and name of the application holding schema on
	// connection, empty for none.
	Holder func(ctx context.Context, connection, schema string) (id, name string)
}

Applications is what a session asks about the applications holding an application database's schemas (#2539): the one whose run role a script's statements log in as, and the one holding a schema a statement was refused on.

type EndpointCaller added in v1.153.0

type EndpointCaller struct {
	UserID string
	Email  string
}

EndpointCaller is who sent the endpoint request a session serves, as its statements' claims carry it (#2403). Both fields are empty on a public endpoint.

type RefusalError

type RefusalError struct {
	Code       string
	RetryAfter time.Duration
	// Text is the result's own text, what Error returns.
	Text string
	// Retryable is the envelope's retryable: the tool says the same call made
	// later is expected to succeed.
	Retryable bool
	// Envelope is the whole structuredContent.error object as the tool wrote
	// it, decoded from JSON: what platform.query(..., on_error = "return")
	// hands the script, and what a recording keeps.
	Envelope map[string]any
}

RefusalError is a tool call that failed with the platform's structured error envelope ({code, category, message, hint, retry_after_seconds}), returned by a Caller as the error so the engine can read the refusal as data. Its Error text is what the script would have been handed before the envelope was read: the result's own text, so a failure the engine does not absorb reaches the author in the tool's words.

The engine waits on a rate_limited refusal, and reads Retryable on every other one: a refusal its tool classified as temporary (mcp-trino's trino_query_failed, #2032) ends a run as the upstream's rather than the script's.

func NewRefusal added in v1.140.0

func NewRefusal(text string, env map[string]any) *RefusalError

NewRefusal is the refusal a recorded or declared failure answers with: text is what Error returns, and env is the envelope it carried.

func (*RefusalError) Error

func (r *RefusalError) Error() string

Error returns the refusal's text as the tool wrote it.

type SessionCaller

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

SessionCaller issues a script's platform calls over one in-memory MCP session against the fully assembled server. It is the production Caller: every host binding a script invokes becomes an ordinary tool call, crossing the same authentication, authorization, gate, rate-limit, and audit middleware an agent's call crosses, with no second implementation to keep in step.

The exceptions are an application database (#2428, #2402), whose calls IsAppDBCall names are answered here against the connection's pool and never reach the server, and a resource read (#2616), answered by the session's own resources/read.

func Connect

func Connect(ctx context.Context, server *mcp.Server, label string) (*SessionCaller, func(), error)

Connect opens an in-memory MCP session against server and returns the SessionCaller that drives it, plus the teardown for both ends. Both call sites hand it straight to scriptrun.Options.Caller.

The identity the session authenticates as comes from ctx, which the caller has already decorated: a draft run carries its author's own identity, a platform run carries the script principal and the version author's captured roles. This function deliberately establishes no identity of its own — there is one place a script's authority is decided, and it is not here. label names the client in the handshake so the two run kinds are distinguishable in logs.

func (*SessionCaller) CallTool

func (c *SessionCaller) CallTool(ctx context.Context, name string, args map[string]any) (map[string]any, error)

CallTool invokes one tool and returns its structured content. A tool that reports an error through the platform's envelope is returned as a *RefusalError, so the engine can pace a rate-limit refusal; the error's text is the result's own either way.

func (*SessionCaller) DeclaresReadOnly

func (c *SessionCaller) DeclaresReadOnly(ctx context.Context, name string) (readOnly, known bool)

DeclaresReadOnly reports whether the server this session is connected to advertises the named tool with MCP's read-only annotation, and whether it advertises the tool at all.

It is the one thing the platform knows about a tool no classification rule names: an MCP gateway connection proxies whatever its upstream serves, under names the upstream chose, and the upstream's own ReadOnlyHint travels with the tool onto this server's listing. The draft's write barrier takes that statement rather than refusing every proxied tool (#1664).

The listing is the SESSION's, so it is already filtered to what this run may see. The annotation is a plain bool in the protocol, so "declared false" and "declared nothing" are one value; only true is a statement, which is why it is the only value that answers read.

type TestDatabases added in v1.153.0

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

TestDatabases answers one script test's application-database calls against throwaway databases built from each connection's migrations (#2407), in place of the recording: a constraint, a trigger or a policy is exercised rather than answered. A test opens one per connection with testing.database; every application-database call it makes after the first is answered here, and a call naming a connection the test did not open is refused rather than answered from the recording, so a test never mixes the two for one database.

func NewTestDatabases added in v1.153.0

func NewTestDatabases(ctx context.Context) *TestDatabases

NewTestDatabases returns the throwaway databases of one test execution. ctx carries the identity the test runs as, which each database is authorized for as the connection itself is. It is nil on a deployment that serves no application database.

func (*TestDatabases) Active added in v1.153.0

func (d *TestDatabases) Active() bool

Active reports whether the test opened a database, after which every application-database call is answered here.

func (*TestDatabases) Call added in v1.153.0

func (d *TestDatabases) Call(ctx context.Context, name string, args map[string]any) (map[string]any, error)

Call answers one application-database call.

func (*TestDatabases) Close added in v1.153.0

func (d *TestDatabases) Close()

Close rolls back the transactions the test left open and drops every database it opened.

func (*TestDatabases) Open added in v1.153.0

func (d *TestDatabases) Open(connection string, schemas []string) error

Open builds connection's throwaway database for the test: its migrations in schemas (every schema when empty) applied from zero, cloned for this test alone. Opening it again with the same schemas is the same database.

Jump to

Keyboard shortcuts

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