mcp

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2026 License: AGPL-3.0 Imports: 18 Imported by: 0 modules, 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.

Documentation

Index

Constants

View Source
const (
	// MaxInFlightPerAuthorization is 8 in flight per authorization.
	MaxInFlightPerAuthorization = 8
	// MaxInFlightPerProcess is 32 across the process.
	MaxInFlightPerProcess = 32
	// ConcurrencyRetryAfterSeconds is what a 429 from the concurrency gate
	// tells a client to wait. A 429 with no Retry-After tells a client to
	// guess, and a guessing client retries too soon.
	ConcurrencyRetryAfterSeconds = 1
)

Concurrency limits (spec section 8.1).

View Source
const (
	MetaKeyCommit    = "app.agent-gm/commit"
	MetaKeySourceURL = "app.agent-gm/source_url"
)

MetaKeyCommit and MetaKeySourceURL carry the AGPL section 13 obligation of spec section 1.4 on the MCP surface.

They live in the `initialize` result's `_meta` rather than in `serverInfo` because the SDK's own `serverInfo` type -- mcp.Implementation -- has fields for a name, a version, a title, a description, icons and a website URL, and none for a build commit. Inventing a `serverInfo.commit` would mean hand-rolling the one result the SDK exists to render. `_meta` is the protocol's own extension point and takes reverse-DNS keys, so this is where a server puts a fact the schema does not have a field for.

View Source
const (
	// ProtocolVersion is what `server/discover` negotiates to. It is NOT what
	// `initialize` answers; see above.
	ProtocolVersion = "2026-07-28"
	// ProtocolVersionCompat is section 8.1's named compatibility revision,
	// and it is also the ceiling of the `initialize` handshake.
	ProtocolVersionCompat = "2025-11-25"
)

The protocol revisions this server speaks (spec section 8.1).

Negotiation is the SDK's from decision D36 onwards: these constants say what the SDK is expected to agree to, and a test drives a real handshake to prove it still does, rather than a switch here deciding it.

**There are two handshakes, and they answer differently.** `initialize` is deprecated in `2026-07-28`, so the SDK will not negotiate that revision over it: `initialize` is CAPPED at `2025-11-25` (`negotiateMutuallySupportedVersion`, mcp/shared.go:67). Asking it for `2026-07-28` is answered `2025-11-25`; asking it for a revision at or below the cap is answered with that revision, as ordinary negotiation. That is the SDK being right rather than this server being wrong. `2026-07-28` is reached only through **`server/discover`** (SEP-2575), which is what a reference client sends. Both are asserted, each against the handshake that really produces it.

`2026-07-28` is available only because the transport is stateless: the SDK refuses every revision from it onwards on a stateful transport (`mcp/streamable.go:871`). The SDK also accepts three revisions older than section 8.1 names -- `2025-06-18`, `2025-03-26` and `2024-11-05` (`mcp/shared.go:58`) -- because supporting the clients still on them is the SDK's job and refusing them would be this package overriding the reference implementation for no gain.

View Source
const AttachmentURIPrefix = "agm://attachments/"

AttachmentURIPrefix is the resource scheme and path.

View Source
const AttachmentURITemplate = "agm://attachments/{attachment_id}"

AttachmentURITemplate is what `resources/templates/list` offers.

View Source
const Instructions = "**This server is one person's Google Messages — possibly more than one\n" +
	"account of it.** Each account is paired directly with an Android phone, the\n" +
	"way the Google Messages web client pairs. Everything you can see here, they\n" +
	"can see in the Messages app on that phone, and everything you send leaves as\n" +
	"a real SMS, MMS or RCS message to a real person. There is no sandbox and no\n" +
	"undo.\n" +
	"\n" +
	"**Accounts.** Call `list_accounts` first if you do not already know which\n" +
	"account you are working in. Each has an ID starting `acct_`, the Google\n" +
	"address it belongs to, a label the owner chose, and a `state`. **If there is\n" +
	"exactly one account you can leave `account_id` out of every call and it will\n" +
	"be used.** If there is more than one, reads without `account_id` cover all of\n" +
	"them, but **a write must name one** — omit it and you get `invalid_request`\n" +
	"listing the accounts to choose from, which you can retry against\n" +
	"immediately. A `conv_` or `msg_` ID already belongs to one account, so you\n" +
	"never need to pass both.\n" +
	"\n" +
	"An account whose `state` is not `connected` is still fully readable — its\n" +
	"history is here — but writes to it are refused with\n" +
	"`unsupported_capability` and `reason: \"not_signed_in\"`. That means the owner\n" +
	"signed it out or its credentials expired; only they can fix it, and no\n" +
	"amount of retrying will.\n" +
	"\n" +
	"**The thing you address is a conversation.** A conversation is a Google\n" +
	"Messages thread: one other person, or a group. It has an ID that starts\n" +
	"`conv_`. Messages in it have IDs that start `msg_`. Every ID here is an\n" +
	"Agent GM ID with a typed prefix — `conv_` conversations, `msg_` messages,\n" +
	"`att_` attachments, `react_` reactions, `part_` people in a thread,\n" +
	"`contact_` contacts, `upl_` uploads, `op_` operations. Google's own IDs are\n" +
	"not accepted in their place.\n" +
	"\n" +
	"Words mean what they mean in Google Messages. A *conversation* is a thread.\n" +
	"A *contact* is somebody in the phone's contact list. *RCS* is the modern\n" +
	"protocol; *SMS/MMS* is the fallback. *Delete* means delete from this\n" +
	"account only — the other person keeps their copy, always.\n" +
	"\n" +
	"1. **Find the conversation.** `list_conversations` with `participant` set\n" +
	"   to a phone number (`+15105550123`, the bare digits, or a national form)\n" +
	"   returns the threads that number is in, newest activity first. Add\n" +
	"   `account_id` to look in one account, or leave it out to look in all of\n" +
	"   them — results carry `account_id` either way. With only a name, use\n" +
	"   `query`, a substring match over the thread name and every participant's\n" +
	"   name and number. `sender: \"me\"` means the owner in whichever account a\n" +
	"   message belongs to, so it works across accounts as well as within one.\n" +
	"   `list_contacts` maps names to\n" +
	"   numbers.\n" +
	"2. **Read it.** `list_messages` with that `conversation_id`. Newest first,\n" +
	"   so the first item is the latest message. Pass the result's `next_cursor`\n" +
	"   back as `cursor` for the next page; page size defaults to 50 and caps at\n" +
	"   100. `search_messages` needs `q`; it searches **every** account unless\n" +
	"   you pass `account_id`.\n" +
	"3. **Reply.** `send_message` with the `conversation_id` and `text`.\n" +
	"   Add `reply_to_message_id` to thread a\n" +
	"   reply — **but replies are an RCS feature; on an `sms_mms` conversation\n" +
	"   that argument is refused with `unsupported_capability` and\n" +
	"   `reason: \"reply_not_supported\"`.** Check the conversation's `type` first,\n" +
	"   or read `capabilities.reply`.\n" +
	"4. **Know whether it arrived.** The result carries a `message_id` and an\n" +
	"   `operation`. Then watch the message's `delivery.state`, which walks\n" +
	"   `sending → sent → delivered → read`. **On SMS it usually stops\n" +
	"   at `sent`, and on group threads it usually stops at `sent`. Delivery and\n" +
	"   read receipts are an RCS feature and a carrier feature; waiting for\n" +
	"   `delivered` on an SMS thread can wait forever.** `sent` means the\n" +
	"   carrier took it, and that is as much as SMS will ever tell you.\n" +
	"5. **Send a photo or a file.** `create_upload` with the filename, mime type\n" +
	"   and byte length; run the `curl` command it returns, with `FILE` replaced\n" +
	"   by the path; then `send_message` with `upload_ids: [\"upl_…\"]` and\n" +
	"   optionally `text` as a caption. An upload is **not** tied to an account —\n" +
	"   the conversation you send it into decides that — but it can be sent only\n" +
	"   once. You cannot attach a file through this protocol any other way, and\n" +
	"   base64 through the model is not acceptable.\n" +
	"6. **Start a new thread.** `start_conversation` with `recipients` as E.164\n" +
	"   phone numbers. One recipient is a direct chat; two or more is a group,\n" +
	"   and `name` is only accepted for a group. **If a thread with exactly\n" +
	"   those recipients already exists you get that thread back and nothing is\n" +
	"   sent** — starting is safe, sending is not.\n" +
	"7. **React, or take something back.** `add_reaction` with `emoji` set to a\n" +
	"   bare emoji — Google offers eleven (👍 😍 😂 😮 😥 😠 👎 🤔 😢 😡 ❤️) and\n" +
	"   anything else is sent as a custom reaction that may not render on the\n" +
	"   recipient's phone. One reaction per person per message: adding a second\n" +
	"   replaces the first. `remove_reaction` takes the same `emoji`, or the\n" +
	"   `reaction_id` you read. `delete_message` and\n" +
	"   `delete_conversation` delete from **this account only** — the recipient\n" +
	"   keeps their copy. There is no delete-for-everyone and no mode to choose.\n" +
	"\n" +
	"**There is no idempotency key to invent.** Every write returns an\n" +
	"`operation` with an id, and status is checked by that id with\n" +
	"`get_operation`. **If a call's result is lost — a timeout, a dropped\n" +
	"connection, a tool error you cannot read — do not send it again. Look\n" +
	"first:** `list_messages` on the conversation, or `list_operations`, will\n" +
	"tell you whether it went. Sending again because you did not see an answer\n" +
	"is how a person gets the same text twice. If a send times out with\n" +
	"`phone_not_responding`, the operation is `pending`, not failed: the server\n" +
	"accepted it and the phone may still send it when it wakes. **Poll\n" +
	"`get_operation`; do not resend.**\n" +
	"\n" +
	"The phone has to be awake and online for anything to happen.\n" +
	"`list_accounts` and `get_session` tell you whether it is: `state` and\n" +
	"`phone_responding`, per account. `get_health` tells\n" +
	"you whether the index is complete (`backfill`) and whether the two things\n" +
	"that break sending are right (`is_default_sms_app`,\n" +
	"`config_version_stale`). If `state` is not `connected`, reads still work\n" +
	"from the local index but writes will fail, and only the owner can fix it.\n" +
	"\n" +
	"A call that is refused comes back as an ordinary result with\n" +
	"`isError: true` and\n" +
	"`structuredContent.error = {code, message, retryable, details}`. Read it\n" +
	"and correct the call rather than repeating it. `not_found` means no such\n" +
	"object. `invalid_request` names the parameter you got wrong in\n" +
	"`details.parameter` or `details.field` — this server refuses a misspelled\n" +
	"filter rather than silently ignoring it. `unsupported_capability` means the\n" +
	"action cannot apply here and `details.reason` says why.\n" +
	"`phone_not_responding` and `rate_limited` are retryable; almost nothing\n" +
	"else is.\n" +
	"\n" +
	"Scopes: `messages:read` gives you `list_accounts`, `list_conversations`,\n" +
	"`get_conversation`, `list_messages`, `get_message`, `message_context`,\n" +
	"`search_messages`, `get_attachment`, `list_contacts`, `get_session` and\n" +
	"`get_health`. A scope covers **every** account this server holds; there is\n" +
	"no per-account permission.\n" +
	"`messages:write` adds `send_message`, `start_conversation`, `mark_read`,\n" +
	"`add_reaction`, `remove_reaction`, `update_conversation`, `create_upload`\n" +
	"and `get_operation`. `messages:delete` adds `delete_message` and\n" +
	"`delete_conversation`. You only see the tools your token allows.\n"

The `instructions` block of spec section 8.3, returned from `initialize`.

It is written for an agent that has never seen this server, has no memory of prior calls, and cannot ask a human. Everything a cold model needs in order not to do harm is in it: that this is one real person's phone, that a send is irreversible, how accounts work, what to do when a result is lost, and what a refusal looks like.

It is reproduced in `docs/mcp.md` under "First five minutes", and section 16 Slice 3 test 20 asserts the two are byte-identical apart from the markdown quoting -- so a client that surfaces instructions to its model has already told it that page, and a fix to one cannot silently leave the other behind.

It is a single constant rather than an assembled string because it is a document, and a document assembled from parts is a document nobody can diff.

View Source
const LostResultSentence = "" /* 152-byte string literal not displayed */

LostResultSentence closes every write tool's description, byte for byte (spec section 8.2).

It is a constant rather than nine copies because a reviewer's planted mutation -- putting a wrong sentence back into a served description -- has to be caught by a lint test, and a lint can only compare against one authority.

It replaced the fresh-key sentence when D38 removed the idempotency key from every tool. The sentence a model needs is no longer "invent a key", which it cannot do stably across a retry; it is what to do when the result of a call never arrived, and the answer is to LOOK before sending again.

View Source
const MaxBodyBytes = apierr.MaxBodyBytes

MaxBodyBytes is section 8.1's 1 MiB bound.

View Source
const Path = "/mcp"

Path is where the endpoint lives.

View Source
const ServerName = "agent-gm"

ServerName is `serverInfo.name`.

Variables

ChallengeScopes is what the `/mcp` challenge tells a client to ask for.

It names `messages:read messages:write` and NOT `messages:delete`, which is section 9.2's literal challenge.

The omission is not an oversight in the spec. `scope` in a challenge is what the client should ASK FOR, and section 9.4 makes exactly those two the default an authorization request carries when the client names no scope. A challenge that also asked for `messages:delete` would send every connector to an approval screen offering to let a model delete the owner's threads, for no better reason than that the scope exists. A client that wants it asks for it; the discovery documents list all three under `scopes_supported`.

View Source
var Exclusions = []Exclusion{
	{
		Route:  "conversations_typing",
		Reason: "no lasting effect and no result a model can act on",
	},
	{
		Route:  "message_attachments_list",
		Reason: "its data is already inside `get_message`; a tool would only add a round trip",
	},
	{
		Route:  "uploads_get",
		Reason: "an agent that has just called `create_upload` already holds everything it would return",
	},
	{
		Route:  "uploads_delete",
		Reason: "an agent that has just called `create_upload` already holds everything it would return",
	},
	{
		Route: "accounts_events",
		Reason: "a stream; MCP tools are request/response. `get_session` and `list_accounts` " +
			"answer the same question at a point in time",
	},
	{
		Route:  "accounts_events_all",
		Reason: "the all-accounts form of the same stream",
	},
	{
		Route: "operations_list",
		Reason: "`get_operation` covers the ID-addressed case, the only one a model reaches: " +
			"it holds the `operation_id` the write returned. Listing operations is an owner's " +
			"audit question, served by `agm operations list`",
	},
	{
		Route: "conversation_messages_list",
		Reason: "the same rows as `list_messages` with `conversation_id` set, which is the argument " +
			"shape a model already has; two tools for one listing would be two places a filter could drift",
	},
}

Exclusions is section 8.2's table, restricted to the routes that carry a messaging scope -- the `admin` and credential rows of that table are covered by the "none of the three" half of the rule and need no entry here.

View Source
var SupportedProtocolVersions = []string{ProtocolVersion, ProtocolVersionCompat}

SupportedProtocolVersions is section 8.1's set, newest first.

View Source
var Tools = []Tool{

	{
		Name:  "list_conversations",
		Scope: authz.ScopeMessagesRead,
		Route: "conversations_list",
		Description: "List the owner's Google Messages threads, newest activity first. " +
			"This is how you find a thread when you have a phone number or a name rather than a `conv_` ID. " +
			"Leave `account_id` out to look in every account the server holds; every row carries its own `account_id` either way.",
		Annotations: readAnnotations,
		Args: []Arg{
			accountIDArg(InQuery, "Leave it out to list threads from every account."),
			{Name: "query", In: InQuery, Schema: nullableStr(""),
				Description: "A literal substring matched against the thread name and every participant's name and number in the local synced database. Does not make a live Google Messages search request. Use it when you have a name rather than a number."},
			{Name: "participant", In: InQuery, Schema: nullableStr(""),
				Description: "A phone number that must be in the thread. E.164 (`+15105550123`), bare digits, or a national form are all accepted and matched against the same normalised value."},
			{Name: "folder", In: InQuery,
				Schema:      enumSchema("", folderVocabulary, true),
				Description: "Only threads in this folder: " + folderVocabulary.sentence() + ". Omit it, or pass null, to list every folder."},
			{Name: "type", In: InQuery,
				Schema:      enumSchema("", conversationTypeVocabulary, true),
				Description: "Only threads of this kind: " + conversationTypeVocabulary.sentence() + ". Omit it, or pass null, to list every kind."},
			{Name: "unread_only", In: InQuery, Schema: nullableBool(""),
				Description: "True to list only threads with unread messages."},
			{Name: "group_only", In: InQuery, Schema: nullableBool(""),
				Description: "True to list only group threads, false to list only one-to-one threads, omitted for both."},
			{Name: "pinned_only", In: InQuery, Schema: nullableBool(""),
				Description: "True to list only pinned threads. False or omitted includes both pinned and unpinned threads."},
			{Name: "after", In: InQuery, Schema: nullableStr(""),
				Description: "Only threads whose latest activity is at or after this RFC 3339 timestamp (inclusive)."},
			{Name: "before", In: InQuery, Schema: nullableStr(""),
				Description: "Only threads whose latest activity is at or before this RFC 3339 timestamp (inclusive). Must not precede after."},
			{Name: "include_deleted", In: InQuery, Schema: nullableBool(""),
				Description: "True to include threads the owner has deleted from this account. They are excluded by default."},
			cursorArg(),
			limitArg(),
		},
	},
	{
		Name:  "get_conversation",
		Scope: authz.ScopeMessagesRead,
		Route: "conversations_get",
		Description: "Read one thread: its name, participants, folder, unread and pinned flags, and its `capabilities` -- which say whether a reply, a reaction or a media send will be accepted here before you attempt one. " +
			"This is the only call that fills in `peer_typing_until`, which is live state and is always null in a listing.",
		Annotations: readAnnotations,
		Args: []Arg{
			{Name: "conversation_id", In: InPath, Required: true, Schema: str(""),
				Description: "The thread's Agent GM ID, starting `conv_`. Google's own thread IDs are not accepted in its place."},
		},
	},
	{
		Name:  "list_messages",
		Scope: authz.ScopeMessagesRead,
		Route: "messages_list",
		Description: "List messages, newest first, so the first row is the latest. " +
			"Pass `conversation_id` to read one thread; leave it out with an `account_id` to read everything recent in an account, or leave both out to read across every account.",
		Annotations: readAnnotations,
		Args: []Arg{
			accountIDArg(InQuery, "Leave it out to read across every account."),
			{Name: "conversation_id", In: InQuery, Schema: nullableStr(""),
				Description: "Only messages in this thread, as a `conv_` ID. A `conv_` ID already belongs to one account, so you never need to pass `account_id` beside it."},
			cursorArg(),
			limitArg(),
			{Name: "direction", In: InQuery,
				Schema:      enumSchema("", directionVocabulary, true),
				Description: "Only messages in this direction: " + directionVocabulary.sentence() + ". Omit it, or pass null, for both."},
			{Name: "sender", In: InQuery, Schema: nullableStr(""),
				Description: "Only messages from this sender: a phone number, or the literal `me`. `me` means the owner in whichever account a message belongs to, so it works across accounts as well as within one."},
			{Name: "after", In: InQuery, Schema: nullableStr(""),
				Description: "Only messages sent at or after this instant, as an RFC 3339 timestamp such as `2026-01-31T09:00:00Z`."},
			{Name: "before", In: InQuery, Schema: nullableStr(""),
				Description: "Only messages sent strictly before this instant, as an RFC 3339 timestamp."},
			{Name: "has_attachment", In: InQuery, Schema: nullableBool(""),
				Description: "True for only messages carrying at least one attachment, false for only messages carrying none."},
			{Name: "delivery_state", In: InQuery,
				Schema:      enumSchema("", deliveryStateVocabulary, true),
				Description: "Only messages in this delivery state: " + deliveryStateVocabulary.sentence() + ". Omit it, or pass null, for every state."},
			{Name: "include_system", In: InQuery, Schema: nullableBool(""),
				Description: "True to include system entries -- somebody joining or leaving a group, and similar notices -- which are excluded by default."},
		},
	},
	{
		Name:  "get_message",
		Scope: authz.ScopeMessagesRead,
		Route: "messages_get",
		Description: "Read one message in full: its text, its sender, its delivery state, its reactions, and the metadata of every attachment it carries. " +
			"The attachment metadata is already here, so there is no separate call to list a message's attachments.",
		Annotations: readAnnotations,
		Args: []Arg{
			{Name: "message_id", In: InPath, Required: true, Schema: str(""),
				Description: "The message's Agent GM ID, starting `msg_`. Google's own message IDs are not accepted in its place."},
		},
	},
	{
		Name:  "message_context",
		Scope: authz.ScopeMessagesRead,
		Route: "messages_context",
		Description: "Read the messages around one message, so a search hit can be understood in its thread without paging to find it. " +
			"Returns `before`, the message itself, and `after`.",
		Annotations: readAnnotations,
		Args: []Arg{
			{Name: "message_id", In: InPath, Required: true, Schema: str(""),
				Description: "The message to centre on, as a `msg_` ID."},
			{Name: "before", In: InQuery, Schema: nullableInt(""),
				Description: "How many messages before it to return. Defaults to 5 and caps at 100."},
			{Name: "after", In: InQuery, Schema: nullableInt(""),
				Description: "How many messages after it to return. Defaults to 5 and caps at 100."},
		},
	},
	{
		Name:  "search_messages",
		Scope: authz.ScopeMessagesRead,
		Route: "search_messages",
		Description: "Full-text search over message text. `q` is required. " +
			"It searches every account the server holds unless you pass `account_id`. " +
			"The result carries a `coverage` block saying whether the index is complete, so a thin answer during a backfill is visible rather than mistaken for an empty one.",
		Annotations: readAnnotations,
		Args: []Arg{
			{Name: "q", In: InQuery, Required: true, Schema: str(""),
				Description: "What to search for. Required."},
			accountIDArg(InQuery, "Leave it out to search every account."),
			{Name: "mode", In: InQuery,
				Schema:      enumSchema("", searchModeVocabulary, true),
				Description: "How to match `q`: " + searchModeVocabulary.sentence() + ". Omit it, or pass null, for `words`."},
			{Name: "conversation_id", In: InQuery, Schema: nullableStr(""),
				Description: "Only hits inside this thread, as a `conv_` ID."},
			{Name: "sender", In: InQuery, Schema: nullableStr(""),
				Description: "Only hits from this sender: a phone number, or the literal `me`."},
			{Name: "after", In: InQuery, Schema: nullableStr(""),
				Description: "Only hits sent at or after this RFC 3339 instant."},
			{Name: "before", In: InQuery, Schema: nullableStr(""),
				Description: "Only hits sent strictly before this RFC 3339 instant."},
			{Name: "has_attachment", In: InQuery, Schema: nullableBool(""),
				Description: "True for only hits on messages carrying an attachment, false for only those carrying none."},
			cursorArg(),
			limitArg(),
		},
	},
	{
		Name:  "get_attachment",
		Scope: authz.ScopeMessagesRead,
		Route: "attachments_get",
		Description: "Read one attachment: its filename, type, byte length and dimensions, plus a short-lived download ticket and a ready-made `curl` command that fetches the bytes. " +
			"A supported image small enough to inline comes back as image content in the result; anything larger or of another kind comes back as an `agm://attachments/...` resource link the client can fetch without putting the bytes through the model. " +
			"The download ticket is returned either way.",
		Annotations: readAnnotations,
		Args: []Arg{
			{Name: "attachment_id", In: InPath, Required: true, Schema: str(""),
				Description: "The attachment's Agent GM ID, starting `att_`, as it appears on a message."},
		},
	},
	{
		Name:        "list_contacts",
		Scope:       authz.ScopeMessagesRead,
		Route:       "contacts_list",
		Description: "List the contacts the phone knows, so a name can be turned into a phone number before searching for a thread.",
		Annotations: readAnnotations,
		Args: []Arg{
			accountIDArg(InQuery, "Leave it out to list contacts from every account."),
			{Name: "query", In: InQuery, Schema: nullableStr(""),
				Description: "A substring matched against the contact's display name and number."},
			{Name: "top", In: InQuery, Schema: nullableBool(""),
				Description: "True to list only the people the owner messages most, which is a much shorter list than every contact."},
			cursorArg(),
			limitArg(),
		},
	},
	{
		Name:  "get_session",
		Scope: authz.ScopeMessagesRead,
		Route: "accounts_get",
		Description: "Read one account's pairing in detail: its `state`, whether the phone is answering, how far its history backfill has got, and its counters. " +
			"Call it when a write was refused and you need to know whether the account is still signed in. " +
			"If the server holds exactly one account you can leave `account_id` out.",
		Annotations: readAnnotations,
		Args: []Arg{
			{Name: "account_id", In: InPath, Schema: nullableStr(""),
				Description: "The account to read, as an `acct_` ID. If the server holds exactly one account you may leave this out and that account is used; with more than one, omitting it is `invalid_request` listing the accounts to choose from."},
		},
	},
	{
		Name:  "get_health",
		Scope: authz.ScopeMessagesRead,
		Route: "health",
		Description: "Read the server's own health and one row per account: how far each backfill has got, whether Google Messages is still the phone's default SMS app (`is_default_sms_app`), and whether the pinned configuration has gone stale (`config_version_stale`). " +
			"Those last two are the settings that break sending, so this is the first call to make when a send fails for no obvious reason.",
		Annotations: readAnnotations,
		Args:        []Arg{},
	},
	{
		Name:  "list_accounts",
		Scope: authz.ScopeMessagesRead,
		Route: "accounts_list",
		Description: "List every Google account this server holds, with its `acct_` ID, the Google address it belongs to, the label the owner chose, and its `state`. " +
			"Call this first when you do not already know which account to work in. " +
			"An account whose `state` is not `connected` is still fully readable; only writes to it are refused.",
		Annotations: readAnnotations,
		Args:        []Arg{},
	},

	{
		Name:  "send_message",
		Scope: authz.ScopeMessagesWrite,
		Route: "messages_send",
		Description: "Send a text, an attachment, or both into an existing thread. **This sends a real SMS, MMS or RCS message to a real person. There is no sandbox and no undo.** " +
			"The result carries a `message_id` and an `operation`; watch the message's `delivery.state` to learn whether it arrived, remembering that on SMS and on groups it usually stops at `sent`. " +
			LostResultSentence,
		Annotations: outboundWriteAnnotations,
		Args: []Arg{
			{Name: "conversation_id", In: InPath, Required: true, Schema: str(""),
				Description: "The thread to send into, as a `conv_` ID. It already names its own account, so there is no `account_id` here."},
			{Name: "text", In: InBody, Schema: nullableStr(""),
				Description: "The message body. Optional only when `upload_ids` is present, in which case it is the caption."},
			{Name: "upload_ids", In: InBody,
				Schema:      &Schema{Type: []string{"array", "null"}, Items: &Schema{Type: "string"}, MaxItems: intPtr(1)},
				Description: "The attachment to send, as a one-element array of an `upl_` ID from `create_upload` whose bytes you have already uploaded. Exactly one element is accepted today; two is refused naming the limit. An upload can be sent only once."},
			{Name: "reply_to_message_id", In: InBody, Schema: nullableStr(""),
				Description: "The `msg_` ID this is a reply to. Replies are an RCS feature: on an `sms_mms` thread this argument is refused with `unsupported_capability` and `reason: \"reply_not_supported\"`, so check the thread's `type` or its `capabilities.reply` first."},
			{Name: "force_rcs", In: InBody, Schema: nullableBool(""),
				Description: "True to refuse to fall back to SMS: if the thread cannot carry RCS the send is refused rather than quietly downgraded."},
		},
	},
	{
		Name:  "start_conversation",
		Scope: authz.ScopeMessagesWrite,
		Route: "conversations_start",
		Description: "Start a thread with one or more phone numbers, or find the one that already exists. " +
			"**If a thread with exactly those recipients already exists you get that thread back and nothing is sent** -- starting is safe, sending is not. " +
			"This is the one write whose target is a phone number rather than an ID, so it is the one that needs `account_id` when the server holds more than one account. " +
			LostResultSentence,
		Annotations: outboundWriteAnnotations,
		Args: []Arg{
			accountIDArg(InBody, "Required when the server holds more than one account; omitting it then is `invalid_request` listing the accounts to choose from. With exactly one account you may leave it out."),
			{Name: "recipients", In: InBody, Required: true,
				Schema:      &Schema{Type: "array", Items: &Schema{Type: "string"}, MinItems: intPtr(1)},
				Description: "The phone numbers to address, in E.164 form such as `+15105550123`. One recipient is a direct chat; two or more is a group."},
			{Name: "name", In: InBody, Schema: nullableStr(""),
				Description: "A name for the new group. Accepted only for a group; supplying it with a single recipient is refused."},
		},
	},
	{
		Name:  "mark_read",
		Scope: authz.ScopeMessagesWrite,
		Route: "conversations_mark_read",
		Description: "Mark a thread read up to and including one message. This tells the other side, on an RCS thread where they have read receipts on, that the owner has seen it. " +
			LostResultSentence,
		Annotations: outboundWriteAnnotations,
		Args: []Arg{
			{Name: "conversation_id", In: InPath, Required: true, Schema: str(""),
				Description: "The thread to mark, as a `conv_` ID."},
			{Name: "message_id", In: InBody, Schema: nullableStr(""),
				Description: "Mark read up to and including this `msg_` ID. Omit it to mark the whole thread read up to its latest message."},
		},
	},
	{
		Name:  "add_reaction",
		Scope: authz.ScopeMessagesWrite,
		Route: "reactions_add",
		Description: "React to a message with an emoji. One reaction per person per message: adding a second replaces the first, which is a change the recipient sees. " +
			LostResultSentence,
		Annotations: outboundWriteAnnotations,
		Args: []Arg{
			{Name: "message_id", In: InPath, Required: true, Schema: str(""),
				Description: "The message to react to, as a `msg_` ID."},
			{Name: "emoji", In: InBody, Required: true, Schema: str(""),
				Description: emojiDescription},
		},
	},
	{
		Name:   "remove_reaction",
		Scope:  authz.ScopeMessagesWrite,
		Routes: []string{"reactions_remove", "reactions_remove_by_id"},
		Description: "Take back a reaction the owner sent. Address it either by `reaction_id`, or by `message_id` plus `emoji`; supplying neither is `invalid_request`. " +
			"Removing somebody else's reaction is refused. " +
			LostResultSentence,
		Annotations: removeReactionAnnotations,
		Args: []Arg{
			{Name: "reaction_id", In: InPath, Schema: nullableStr(""),
				Description: "The reaction to remove, as a `react_` ID read from the message. Supply this, or `message_id` plus `emoji`."},
			{Name: "message_id", In: InPath, Schema: nullableStr(""),
				Description: "The message the reaction is on, as a `msg_` ID. Supply this with `emoji`, or supply `reaction_id` instead."},
			{Name: "emoji", In: InPath, PathParam: "emoji", Schema: nullableStr(""),
				Description: "Which reaction to remove, as the same bare emoji that was added. " + emojiDescription},
		},
	},
	{
		Name:  "update_conversation",
		Scope: authz.ScopeMessagesWrite,
		Route: "conversations_update",
		Description: "Change a thread's own filing: which folder it is in, whether it is pinned, and whether it counts as unread. This changes the owner's copy only and nothing leaves the building. " +
			"A change to a state the thread is already in answers `changed: false` and does nothing. " +
			LostResultSentence,
		Annotations: localWriteAnnotations,
		Args: []Arg{
			{Name: "conversation_id", In: InPath, Required: true, Schema: str(""),
				Description: "The thread to change, as a `conv_` ID."},
			{Name: "folder", In: InBody,
				Schema:      enumSchema("", writableFolderVocabulary, true),
				Description: "Move the thread to this folder: " + writableFolderVocabulary.sentence() + ". Omit it to leave the folder alone."},
			{Name: "pinned", In: InBody, Schema: nullableBool(""),
				Description: "True to pin the thread to the top of the owner's list, false to unpin it. Omit it to leave pinning alone."},
			{Name: "unread", In: InBody, Schema: nullableBool(""),
				Description: "True to mark the thread unread, false to mark it read. Omit it to leave the flag alone."},
		},
	},
	{
		Name:  "create_upload",
		Scope: authz.ScopeMessagesWrite,
		Route: "uploads_create",
		Description: "Reserve an upload for a file you want to send, and get back a ticket and a ready-made `curl` command. " +
			"Run that command with `FILE` replaced by the path, then pass the `upl_` ID to `send_message` as `upload_ids`. " +
			"An upload is not tied to an account -- the thread you send it into decides that -- and it can be sent only once. " +
			"This is the only way to attach a file; base64 through the model is not accepted. Nothing leaves the building until you send it. " +
			LostResultSentence,
		Annotations: localWriteAnnotations,
		Args: []Arg{
			{Name: "filename", In: InBody, Schema: nullableStr(""),
				Description: "The file's name, which the recipient sees."},
			{Name: "mime_type", In: InBody, Required: true, Schema: str(""),
				Description: "The file's media type, such as `image/jpeg`. It is checked against the types Google Messages accepts at reservation time, so an unsupported type is refused now rather than at send time."},
			{Name: "size_bytes", In: InBody, Required: true, Schema: &Schema{Type: "integer"},
				Description: "The file's exact byte length. Required. A body that is longer or shorter than this spends the reservation and is refused, so measure the file rather than estimating."},
			{Name: "sha256", In: InBody, Schema: nullableStr(""),
				Description: "The file's SHA-256, lowercase hex. Optional; when given, a body whose digest differs is refused."},
		},
	},
	{
		Name:  "get_operation",
		Scope: authz.ScopeMessagesWrite,
		Route: "operations_get",
		Description: "Read one operation a write of yours created, by the `op_` ID that write returned. " +
			"This is how you learn whether a send that timed out with `phone_not_responding` eventually went: the operation is `pending`, not failed, and the phone may still send it when it wakes. **Poll this; do not resend.** " +
			"It is a read, but it is gated on `messages:write` because it exposes only operations the caller created, and `messages:write` is the scope that creates them.",
		Annotations: readAnnotations,
		Args: []Arg{
			{Name: "operation_id", In: InPath, Required: true, Schema: str(""),
				Description: "The operation to read, as an `op_` ID returned by a write. Another authorization's operation answers `not_found`."},
		},
	},

	{
		Name:  "delete_message",
		Scope: authz.ScopeMessagesDelete,
		Route: "messages_delete",
		Description: "Delete one message from this account only. **The recipient keeps their copy, always** -- there is no delete-for-everyone and nothing to choose. " +
			LostResultSentence,
		Annotations: deleteAnnotations,
		Args: []Arg{
			{Name: "message_id", In: InPath, Required: true, Schema: str(""),
				Description: "The message to delete, as a `msg_` ID."},
		},
	},
	{
		Name:  "delete_conversation",
		Scope: authz.ScopeMessagesDelete,
		Route: "conversations_delete",
		Description: "Delete a whole thread and its messages from this account only. **The other person keeps their copy, always.** This cannot be undone from here. " +
			LostResultSentence,
		Annotations: deleteAnnotations,
		Args: []Arg{
			{Name: "conversation_id", In: InPath, Required: true, Schema: str(""),
				Description: "The thread to delete, as a `conv_` ID."},
		},
	},
}

Tools is the whole catalogue, in the order section 8.2 tables it.

Functions

func Challenge

func Challenge(publicURL string) string

Challenge is the `WWW-Authenticate` a 401 and a 403 from `/mcp` both carry.

The two answers are deliberately distinct -- no token is `401`, a valid token with no messaging scope is `403 insufficient_scope` -- but the challenge itself is the same string, because it says the same thing to the same reader: here is where to authorize, and here is what to ask for.

The FORMAT is the SDK's, not ours (decision D36): it is what `auth.RequireBearerToken` emits, which is why there is no `realm` parameter any more. A test drives a real `RequireBearerToken` and asserts this function returns exactly what it wrote, so the SDK stays the authority and a bump that changes the format fails that test rather than a connector.

func ExcludedRoutes

func ExcludedRoutes() map[string]string

ExcludedRoutes is the exclusion set, by route name.

func IsMessagingScope

func IsMessagingScope(s api.Scope) bool

IsMessagingScope reports whether a route's scope is one of the three messaging scopes -- the routes the three-way rule is about.

func Mount

func Mount(next http.Handler, h *Handler) http.Handler

Mount returns an http.Handler that serves `/mcp` from h and everything else from next.

It is a wrapper rather than a route in the api inventory on purpose: `/mcp` is not a `/v1` route, it does not answer the section 7.1 envelope on success, and its pre-transport checks run in an order the REST chain does not have. Putting it in the inventory would make the two-way table test of section 16 Slice 3 test 16 -- which is about `/v1` routes -- have to special-case its own endpoint.

func ResourceRoutes

func ResourceRoutes() map[string]string

ResourceRoutes is the routes served as an MCP **resource** rather than as a tool: bytes belong in a resource so a client can fetch them without putting them through the model's context (spec section 8.2).

func ServerVersion

func ServerVersion(version, commit string) string

ServerVersion is `serverInfo.version`: the release version with the built commit as semver build metadata, `0.1.0+abc1234`.

The commit rides in the version string because there is nowhere else it can go that a real client will read. `mcp.Implementation` -- the SDK's `serverInfo` -- has no field for a build commit, and `_meta` does not survive: from protocol 2026-07-28 a client discovers the server with `server/discover`, and the SDK's own client throws away every `_meta` key of that result except `io.modelcontextprotocol/serverInfo` (mcp/client.go:428-441, `decodeMetaValue`). So a build fact placed in `_meta` reaches a raw HTTP caller and no reference client at all, which would leave section 1.4's AGPL obligation unmet on the surface that matters. Build metadata after a `+` is what semver has for exactly this, and `serverInfo.websiteUrl` carries the source URL beside it.

The `_meta` keys are still written, for a caller reading the wire directly.

func ToolRoutes

func ToolRoutes() map[string]string

ToolRoutes is every route reachable through a tool, mapped to the tool that reaches it.

Types

type Annotations

type Annotations struct {
	ReadOnlyHint    bool `json:"readOnlyHint"`
	DestructiveHint bool `json:"destructiveHint"`
	IdempotentHint  bool `json:"idempotentHint"`
	OpenWorldHint   bool `json:"openWorldHint"`
}

Annotations are section 8.2's table, accurate rather than conventional.

They are serialised in full -- no `omitempty` -- because `false` is a claim and an absent key is not. A client that had to guess whether a missing `destructiveHint` meant "no" or "unstated" would guess wrong on the tools where it matters.

type Arg

type Arg struct {
	// Name is the argument as a model writes it. It is the same word the
	// route uses (spec section 11.3): there is no renaming layer.
	Name string
	// Description is mandatory. Section 16 Slice 3 test 15 fetches
	// `tools/list` from a running server, counts the arguments and counts
	// the descriptions, and requires them equal.
	Description string
	// Schema is the argument's JSON Schema.
	Schema *Schema
	// Required puts the argument in the input schema's `required`.
	Required bool
	// In is where it goes on the route.
	In ArgIn
	// PathParam overrides the route path parameter name when it differs
	// from Name. It differs exactly once, on `remove_reaction`, whose
	// `emoji` is a path segment on one of its two routes.
	PathParam string
}

Arg is one tool argument.

type ArgIn

type ArgIn int

ArgIn is where an argument goes on the REST route.

const (
	// InPath binds a `{...}` segment of the route's path.
	InPath ArgIn = iota
	// InQuery becomes a query parameter.
	InQuery
	// InBody becomes a JSON body field.
	InBody
)

type Config

type Config struct {
	// API is the REST server whose handlers every tool call runs.
	API *api.Server
	// Authz authenticates the bearer and resolves the client source.
	Authz *authz.Service
	// PublicURL is AGENT_GM_PUBLIC_URL. The `Origin` check compares against
	// it, and every URL handed out is built from it.
	PublicURL string
	// The build facts the `initialize` result reports. `Commit` and
	// `SourceURL` are the AGPL section 13 obligation of spec section 1.4, and
	// section 16 Slice 3 test 28 asserts they equal the built commit.
	Version   string
	Commit    string
	SourceURL string
	// Log receives one line per refusal. It never writes to stdout.
	Log func(msg string, kv ...any)
	// FaultAfterChainForTest is a FAULT SEAM, nil in production: it runs
	// after the chain and before ServeHTTP returns.
	//
	// It is here because the thing worth proving cannot be reached any other
	// way. A refusal at 400 or above is BUFFERED and reaches the socket only
	// from the deferred finish(), so the property is "a panic after the
	// buffer is filled still delivers it", and no client input can make the
	// SDK panic on demand. The repository already uses this idiom -- see
	// authz's BeforeRefreshTx -- and a seam placed exactly where the window
	// is beats a test that reaches around the production path and proves
	// nothing about it.
	//
	// It is a Config field consumed by New, not a setter, so that it cannot
	// be written while the handler is serving: a post-construction setter is
	// safe only by convention, and this package puts everything explicit in
	// Config already.
	FaultAfterChainForTest func()
}

Config is what the handler collaborates with. Every field is explicit so a test can build a whole MCP server over two fakes and its own clock.

type Exclusion

type Exclusion struct {
	// Route is the inventory name.
	Route string
	// Reason is section 8.2's reason, in its own words.
	Reason string
}

Exclusion is one messaging route deliberately not served as a tool.

type Handler

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

Handler serves `/mcp`.

func New

func New(cfg Config) *Handler

New builds the handler.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP runs the chain.

type Schema

type Schema struct {
	// Type is a string or an array of strings; a nullable value is
	// `["string", "null"]`.
	Type any `json:"type,omitempty"`
	// Description is mandatory on every argument (section 8.2) and on every
	// value of a closed vocabulary.
	Description string `json:"description,omitempty"`

	Properties map[string]*Schema `json:"properties,omitempty"`
	Required   []string           `json:"required,omitempty"`
	// AdditionalProperties is a pointer so that `false` is serialised and
	// an unset value is omitted.
	AdditionalProperties *bool `json:"additionalProperties,omitempty"`

	Items *Schema `json:"items,omitempty"`

	Enum  []any     `json:"enum,omitempty"`
	OneOf []*Schema `json:"oneOf,omitempty"`
	Const any       `json:"const,omitempty"`

	Format   string `json:"format,omitempty"`
	MinItems *int   `json:"minItems,omitempty"`
	MaxItems *int   `json:"maxItems,omitempty"`
}

Schema is a JSON Schema fragment.

func (*Schema) MarshalJSON

func (s *Schema) MarshalJSON() ([]byte, error)

MarshalJSON is here only so that a Schema with no fields set serialises as `{}` -- an unconstrained schema -- rather than as `null`.

type Tool

type Tool struct {
	Name        string
	Description string
	// Scope is what a caller must hold to see it in `tools/list` and to call
	// it. Visibility is not authorization: `tools/call` checks again.
	Scope authz.Scope
	// Route is the inventory name of the REST route this tool is a facade
	// over. It is empty on `remove_reaction` alone, which addresses one of
	// two routes depending on which arguments arrived.
	Route string
	// Routes is every route this tool can reach. It is what the two-way
	// table test of section 16 Slice 3 test 16 walks, so a tool that picks
	// its route at call time still accounts for both.
	Routes []string
	Args   []Arg
	Annotations
}

Tool is one entry of the catalogue.

func ToolByName

func ToolByName(name string) (Tool, bool)

ToolByName looks a tool up.

func VisibleTools

func VisibleTools(auth *authz.Authorization) []Tool

VisibleTools is the subset of the catalogue an authorization may use.

`tools/list` returns only these, so a model is never invited to attempt something that will be refused (spec section 8.2). `tools/call` checks again: visibility is not authorization, and a client may call a name it learned elsewhere.

func (Tool) InputSchema

func (t Tool) InputSchema() *Schema

InputSchema renders the tool's closed input schema.

func (Tool) IsWrite

func (t Tool) IsWrite() bool

IsWrite reports whether this is a **write tool** in the sense section 8.2 uses the phrase: one that changes something, and whose description therefore ends with LostResultSentence.

It is decided by the annotations the tool actually serves rather than by a list kept beside them, because a list beside them is a list that can disagree with them -- and the annotations are the thing a client reads. `get_operation` is gated on `messages:write` and is not one: it carries the read annotations because it creates nothing, so there is nothing to repeat.

func (Tool) OutputSchema

func (t Tool) OutputSchema() *Schema

OutputSchema builds the tool's declared output schema.

It describes BOTH shapes a call can answer with, because both are results: the success envelope, and the section 8.2 refusal that carries the REST error in `error` and sets `isError: true`. A schema that described only the success case would be a schema every refusal violated -- and a strict client validates `structuredContent` against it, so it would turn a refusal a model could have read into a client-side protocol failure. That is exactly the outcome section 8.2's isError rule exists to prevent, so the schema has to say the refusal is legitimate rather than merely the code doing it.

The two are a `oneOf` rather than a union of optional keys, so that a result carrying both, or neither, is invalid.

type Vocabulary

type Vocabulary struct {
	// Name is what the vocabulary is called in prose, for the sentence that
	// names the values in the argument's own description.
	Name   string
	Values []VocabularyValue
}

Vocabulary is one closed vocabulary: the accepted values, each with the description that goes on its `const`.

type VocabularyValue

type VocabularyValue struct {
	Value       string
	Description string
}

VocabularyValue is one accepted value and what it means.

Jump to

Keyboard shortcuts

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