Documentation
¶
Overview ¶
Package adminmcp answers an operator's questions about lobbies and players through Model Context Protocol tools. It reads only the lobby_* tables, through the GORM records in package postgres, so any game that uses the lobby can register the tools on its own admin server and add its own beside them. Nothing in it writes: every tool runs in a read-only transaction on a connection whose sessions are read-only too.
Index ¶
- Constants
- Variables
- func AddTools(server *mcp.Server, database *gorm.DB, options Options)
- func CheckCredentialsHidden(transaction *gorm.DB) error
- func OpenDatabase(ctx context.Context, url string, logger *slog.Logger) (*gorm.DB, error)
- func ReadOnly(ctx context.Context, database *gorm.DB, read func(transaction *gorm.DB) error) error
- func ReadOnlyAnnotations(title string) *mcp.ToolAnnotations
- func SQLTransaction(transaction *gorm.DB) (*sql.Tx, error)
- type FindPlayersInput
- type Games
- type GetLobbyInput
- type ListLobbiesInput
- type LobbyCount
- type LobbyDetail
- type LobbyList
- type LobbySummary
- type Member
- type Options
- type Overview
- type Player
- type PlayerList
- type PlayerLobby
- type RosterPlace
- type Session
- type Team
Constants ¶
const ( DefaultListLimit = 50 MaxListLimit = 200 DefaultPlayerLimit = 20 MaxPlayerLimit = 100 )
The tools' limits.
const StatementTimeout = 5 * time.Second
StatementTimeout bounds every statement the tools run, including the statements an operator writes.
const ToolTimeout = 30 * time.Second
ToolTimeout bounds one tool call, which may run several statements. It backs up the statement timeout from the client side.
Variables ¶
var ErrCredentialsColumnChanged = errors.New("lobby_sessions has no bearer_hash column any more, so the read-only role's column grants " +
"may no longer hide its credentials; operator SQL is refused until the grants are updated for the new columns and applied again")
ErrCredentialsColumnChanged refuses operator SQL when lobby_sessions has no bearer_hash column any more, so the column grants that hide its credentials may no longer match it.
var ErrCredentialsReadable = errors.New("the database role can read lobby_sessions.bearer_hash although it is neither a superuser " +
"nor the table's owner, so its grants are out of date, for example after a migration recreated the table; " +
"operator SQL is refused until the role's grants are applied again")
ErrCredentialsReadable refuses operator SQL on a role that can read the sessions' bearer hashes although it should not.
Functions ¶
func AddTools ¶
AddTools registers overview, list_lobbies, get_lobby and find_players on server. Each call reads database, the lobby's, in a read-only transaction; see ReadOnly.
func CheckCredentialsHidden ¶
CheckCredentialsHidden returns ErrCredentialsReadable when a role that should not read bearer hashes can, such as a read-only role whose grants a migration has outrun, and ErrCredentialsColumnChanged when bearer_hash was renamed or dropped, for every role, so a change to the table is noticed. Run it before any SQL an operator writes. It reads catalogs only, so it runs as plain SQL.
func OpenDatabase ¶
OpenDatabase connects to url with a single connection, so the server never holds more than one of the database's connection slots. Every session it opens starts read-only, with default_transaction_read_only on and a statement_timeout of StatementTimeout, whatever the role may do. GORM logs failed and slow queries through logger, with placeholders instead of values; logger must not write to stdout, which carries the MCP stream.
Statements always use PostgreSQL's extended protocol, which runs exactly one statement per query, even when url asks for the simple protocol.
A superuser, such as a local development role, can do much that a read-only transaction doesn't stop, such as reading server files or ending other sessions. Its sessions therefore SET ROLE pg_read_all_data, which reads every table and nothing more, and logger warns once. That is best-effort: a statement may switch the role back with set_config for its own duration. Only a role that is not a superuser, such as the production read-only role, makes the server fully read-only.
func ReadOnly ¶
ReadOnly runs read in a read-only transaction within ToolTimeout. The transaction is always rolled back, never committed, so a SET that a statement ran ends with it and the next tool call starts from the session's read-only defaults again.
Session-level advisory locks outlive the rollback, and the server keeps its one connection, so a pg_advisory_lock that a statement took would be held until the server exits, blocking whoever waits for the same lock, such as the migrations. ReadOnly therefore holds the connection for the whole call and releases every advisory lock on it afterwards. A connection where that fails is closed, which releases them too.
func ReadOnlyAnnotations ¶
func ReadOnlyAnnotations(title string) *mcp.ToolAnnotations
ReadOnlyAnnotations mark a tool as one that changes nothing and reads only the database. Every admin tool carries them.
func SQLTransaction ¶
SQLTransaction returns the database/sql transaction behind a transaction that ReadOnly began, for a statement that GORM must not rewrite, such as one an operator wrote. Run such a statement only in a form that can't be a command, such as a cursor's query: SET TRANSACTION READ WRITE as the transaction's first statement would make it read-write.
Types ¶
type FindPlayersInput ¶
type FindPlayersInput struct {
PlayerID string `json:"player_id,omitempty" jsonschema:"The player's ID, a UUID."`
DisplayName string `json:"display_name,omitempty" jsonschema:"Part of a display name, matched without regard to case, instead of player_id."`
Limit int `json:"limit,omitempty" jsonschema:"The most players to return, 20 by default and at most 100."`
}
FindPlayersInput names the players to find.
type Games ¶
type Games interface {
// Overview returns the game's counts for the overview tool, which shows
// them under "games".
Overview(ctx context.Context, now time.Time) (any, error)
// GameIDs returns the ID of the game that each of lobbyIDs is linked to,
// leaving out lobbies without one. The tools show it as game_id.
GameIDs(ctx context.Context, lobbyIDs []string) (map[string]any, error)
}
Games adds a game's own data to the lobby tools' answers. A game keeps its data in a database of its own, never the lobby's, so it reads there itself, with the tool call's context.
type GetLobbyInput ¶
type GetLobbyInput struct {
LobbyID string `json:"lobby_id,omitempty" jsonschema:"The lobby's ID, a UUID."`
JoinCode string `json:"join_code,omitempty" jsonschema:"The lobby's join code, instead of lobby_id."`
GameKey string `json:"game_key,omitempty" jsonschema:"The lobby's game, when a join code is used by several games."`
}
GetLobbyInput names one lobby.
type ListLobbiesInput ¶
type ListLobbiesInput struct {
GameKey string `json:"game_key,omitempty" jsonschema:"Only this game's lobbies, such as island-battles."`
Phase string `json:"phase,omitempty" jsonschema:"Only lobbies in this phase: waiting, started or closed."`
ActiveOnly bool `json:"active_only,omitempty" jsonschema:"Only lobbies with at least one connected member."`
Limit int `json:"limit,omitempty" jsonschema:"The most lobbies to return, 50 by default and at most 200."`
}
ListLobbiesInput filters list_lobbies.
type LobbyCount ¶
type LobbyCount struct {
GameKey string `json:"game_key"`
Phase string `json:"phase"`
Count int `json:"lobby_count"`
}
LobbyCount counts one game's lobbies in one phase.
type LobbyDetail ¶
type LobbyDetail struct {
LobbySummary
GameSettings any `json:"game_settings" jsonschema:"The settings the lobby was created with."`
Teams []Team `json:"teams"`
Members []Member `json:"members"`
StartRoster []RosterPlace `json:"start_roster" jsonschema:"Who started the game, on which team. Empty until the lobby starts."`
// RetentionDeletesAt is the earlier of the idle and the age deadline.
RetentionDeletesAt time.Time `` /* 172-byte string literal not displayed */
}
LobbyDetail is get_lobby's answer.
type LobbyList ¶
type LobbyList struct {
Lobbies []LobbySummary `json:"lobbies"`
// Matching counts every lobby that matched, before the limit.
Matching int `json:"matching" jsonschema:"Lobbies that matched, before the limit."`
Truncated bool `json:"truncated" jsonschema:"Whether the limit left lobbies out."`
}
LobbyList is list_lobbies' answer.
type LobbySummary ¶
type LobbySummary struct {
ID string `json:"id"`
Name string `json:"name"`
JoinCode string `json:"join_code"`
GameKey string `json:"game_key"`
Phase string `json:"phase"`
Round int64 `json:"round" jsonschema:"The lobby's round, from 1. It goes up each time a member reopens the lobby after its game."`
Capacity int `json:"capacity" jsonschema:"The members the lobby holds: its number of teams, since a team holds one member."`
MemberCount int `json:"member_count" jsonschema:"Active members, who hold a seat, connected or not."`
ConnectedMemberCount int `json:"connected_member_count" jsonschema:"Active members with a lease that has not expired or been released."`
HostDisplayName *string `json:"host_display_name"`
CreatedAt time.Time `json:"created_at"`
LastConnectedAt time.Time `json:"last_connected_at" jsonschema:"The last time a member created, joined, heartbeated, released a lease or left."`
RoundStartedAt time.Time `` /* 172-byte string literal not displayed */
GameID any `json:"game_id" jsonschema:"The newest game started from the lobby, or null."`
}
LobbySummary is one lobby in list_lobbies, and the head of get_lobby.
type Member ¶
type Member struct {
ID string `json:"id"`
PlayerID string `json:"player_id"`
DisplayName string `json:"display_name"`
Kind string `` /* 192-byte string literal not displayed */
TeamID *string `json:"team_id"`
TeamName *string `json:"team_name"`
Ready bool `json:"ready"`
Active bool `json:"active" jsonschema:"Whether the member holds a seat. A member who left or whose grace ran out is inactive."`
Connected bool `json:"connected"`
LeaseExpiresAt *time.Time `json:"lease_expires_at" jsonschema:"When the member's latest unreleased lease expires, or null."`
DisconnectedUntil *time.Time `json:"disconnected_until" jsonschema:"The end of the grace period of a member whose leases ended, or null."`
JoinedAt time.Time `json:"joined_at"`
}
Member is one of a lobby's memberships, active or not.
type Options ¶
type Options struct {
// Clock says when "now" is. Nil uses the system clock.
Clock domain.Clock
// LobbyRetention returns the periods after which retention deletes a
// game's lobbies. Nil uses the lobby's defaults.
LobbyRetention func(gameKey string) domain.LobbyRetention
// Games adds a game's data. Nil leaves game counts and game IDs out.
Games Games
// GamesOverview describes what Games.Overview counts, for the overview
// tool's description, such as "Island Battles games running and finished".
GamesOverview string
}
Options configure AddTools. The zero value works.
type Overview ¶
type Overview struct {
Now time.Time `json:"now"`
LobbyCount int `json:"lobby_count"`
LobbiesByGameAndPhase []LobbyCount `json:"lobbies_by_game_and_phase"`
ActiveLobbyCount int `json:"active_lobby_count" jsonschema:"Lobbies with at least one connected member."`
ConnectedMemberCount int `json:"connected_member_count" jsonschema:"Members connected now, across all lobbies."`
LiveSessionCount int `json:"live_session_count" jsonschema:"Guest sessions that have not expired."`
Games any `json:"games,omitempty" jsonschema:"The game's own counts."`
}
Overview is the overview tool's answer.
type Player ¶
type Player struct {
ID string `json:"id"`
DisplayName string `json:"display_name"`
CreatedAt time.Time `json:"created_at"`
LiveSessions []Session `json:"live_sessions"`
Lobbies []PlayerLobby `json:"lobbies"`
RosterPlaces []RosterPlace `json:"roster_places" jsonschema:"The player's places on started lobbies' start rosters."`
}
Player is one player that find_players found.
type PlayerList ¶
type PlayerList struct {
Players []Player `json:"players"`
Truncated bool `json:"truncated" jsonschema:"Whether the limit left players out."`
}
PlayerList is find_players' answer.
type PlayerLobby ¶
type PlayerLobby struct {
LobbyID string `json:"lobby_id"`
LobbyName string `json:"lobby_name"`
GameKey string `json:"game_key"`
Phase string `json:"phase"`
DisplayName string `json:"display_name" jsonschema:"The player's name in this lobby."`
Kind string `json:"kind" jsonschema:"human for a person, seat for a seat that no person plays, such as a game's bot."`
TeamID *string `json:"team_id"`
Ready bool `json:"ready"`
Active bool `json:"active"`
Connected bool `json:"connected"`
}
PlayerLobby is a player's membership in one lobby.
type RosterPlace ¶
type RosterPlace struct {
LobbyID string `json:"lobby_id"`
PlayerID string `json:"player_id"`
DisplayName *string `json:"display_name"`
MemberID string `json:"member_id"`
TeamID string `json:"team_id"`
TeamName *string `json:"team_name"`
TeamOrder int `json:"team_order"`
}
RosterPlace is one place on a started lobby's start roster.