tools

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the about handler for the system.about verb (CR-0067), a read-only, no-Graph verb that returns a snapshot of build identity and host environment metadata in three output tiers.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the add_account MCP tool, which registers a new Microsoft account in the account registry. It creates a per-account credential with isolated token cache and auth record, performs inline authentication using MCP Elicitation (URL mode for browser, form mode for device code), creates a Graph client, and registers the account for use by other tools.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file implements the shared conservative-fold helper that derives an aggregate domain tool's five MCP annotations from the set of verbs actually registered for that domain (CR-0068). The four domain tools (calendar, mail, account, system) publish a single tool-granularity annotation each, yet host many verbs whose individual read-only, destructive, idempotent and open-world classifications differ. Publishing a static annotation is wrong in at least one supported gated configuration, so the aggregate is computed here as a pure function of the registered verb set.

The per-verb classification lives in each Verb's Annotations field, which is a slice of opaque mcp.ToolOption closures. The accessors below materialise those closures by applying them to a throwaway mcp.Tool and reading the resulting ToolAnnotation struct, rather than attempting to inspect the closures directly.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the cancel_meeting MCP tool, which cancels a meeting on the authenticated user's calendar via the Microsoft Graph API. Only the meeting organizer can cancel; non-organizers receive an access denied error from the Graph API. An optional comment parameter allows the organizer to include a custom cancellation message sent to all attendees.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides a helper function to retrieve the Graph client from the request context. Tool handlers call GraphClient at the start of each invocation to obtain the per-request client injected by the AccountResolver middleware.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the complete_auth MCP tool, a fallback for MCP clients that do not support elicitation. When the auth_code authentication method is active and the middleware cannot elicit the redirect URL inline, it instructs the user to call this tool with the nativeclient redirect URL from the browser's address bar. The tool extracts the authorization code and exchanges it for tokens via the AuthCodeFlow interface.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the mail_create_draft MCP tool, which creates a new message in the authenticated user's Drafts folder via POST /me/messages on the Microsoft Graph API. The draft is not sent: it is left in Drafts for the user to review, edit, and send manually from Outlook.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the create_event MCP tool, which creates a new personal calendar event (without attendees) via the Microsoft Graph API. It supports subject, start/end with timezones, body (HTML/text auto-detection), location, Teams online meetings, all-day events, importance, sensitivity, free/busy status, categories, recurrence patterns, and reminders. To create an event with attendees, use calendar_create_meeting instead.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the mail_create_forward_draft MCP tool, which creates a forward draft via POST /me/messages/{id}/createForward on the Microsoft Graph API. The draft is not sent: it is left in the user's Drafts folder for review and manual send.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the create_meeting MCP tool definition, which creates a new calendar meeting (event with attendees) via the Microsoft Graph API. The tool reuses HandleCreateEvent for its handler logic; only the tool definition differs from create_event. The attendees parameter is required, and the description includes unconditional confirmation guidance for attendee-affecting operations.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the mail_create_reply_draft MCP tool, which creates a reply draft (with correct threading headers) via POST /me/messages/{id}/createReply or /createReplyAll on the Microsoft Graph API. The draft is not sent: it is left in the user's Drafts folder for review and manual send.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the mail_delete_draft MCP tool, which permanently deletes a draft message via DELETE /me/messages/{id} on the Microsoft Graph API. The handler first verifies isDraft=true and refuses to delete sent or received messages.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the delete_event MCP tool, which removes a calendar event from the authenticated user's calendar via the Microsoft Graph API. When the organizer deletes a meeting, cancellation notices are automatically sent to attendees. When an attendee deletes, the event is removed only from their own calendar.

Package tools — this file builds the union of per-verb parameter schemas for a domain aggregate tool (CR-0060 follow-up: parameter-passthrough fix).

MCP clients only forward call arguments declared in the tool's InputSchema. Without this union the aggregate tool exposes only `operation`, so per-verb parameters such as `label` or `message_id` are stripped before reaching the dispatcher. Per-verb required-ness is intentionally dropped here because each parameter is required only for some verbs; handlers continue to validate required arguments at call time.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the description composer for domain aggregate tools (CR-0060). It builds the top-level tool description that lists every registered verb with its one-line summary, and constructs the operation enum passed to mcp.NewTool as a JSON Schema constraint.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file defines the Verb registry type used by the Phase 1 dispatcher scaffolding (CR-0060). A Verb represents a single operation within a domain aggregate tool: it carries the operation name, a one-line summary, the handler function, the MCP tool option annotations, and the JSON Schema properties for operation-specific parameters.

CR-0065 extends Verb with Description, Examples, and SeeDocs so that the registry is the single source of truth for per-verb reference content rendered by system.help (and per-domain help). Every verb MUST have a non-empty Description.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file implements RegisterDomainTool, the single entry point for registering a domain aggregate tool with the MCP server (CR-0060 Phase 1). It also contains the dispatch handler that routes incoming requests to the appropriate Verb handler based on the required `operation` parameter.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server. Each tool handler interacts with the Microsoft Graph API to perform calendar operations (list, get, search, create, update, delete, cancel, respond, reschedule) and their meeting variants for attendee-focused operations. Tool definitions and handlers are registered by the server package during startup.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides shared helpers used by the mail draft management tools (mail_create_draft, mail_create_reply_draft, mail_create_forward_draft, mail_update_draft). The helpers convert comma-separated recipient strings to Graph SDK Recipientable slices, build ItemBody from content/content_type parameters, and format draft confirmation text.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the mail_get_attachment MCP tool, which downloads an email attachment's metadata and base64-encoded content via the Microsoft Graph API. A configurable size limit prevents unbounded memory allocation.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the mail_get_conversation MCP tool, which retrieves all messages in an email conversation thread in chronological order via the Microsoft Graph API. The caller may supply either a message_id (from which the conversationId is resolved) or a conversation_id directly. Results are returned using the three-tier output model (text/summary/raw).

Package tools — this file implements the system.get_docs verb handler (CR-0061 Phase 2). It fetches a document (or a specific section) from the embedded bundle by slug, with optional section slicing by heading anchor and optional output-tier selection (text default, raw markdown).

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the get_event MCP tool, which retrieves full details of a single calendar event by its ID via the Microsoft Graph API. The response includes all event fields including body content, attendees with response status, recurrence patterns, and metadata timestamps.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the get_free_busy MCP tool, which queries the CalendarView endpoint to determine when a user is busy within a specified time range. Events where showAs equals "free" are filtered out, and the remaining events are returned as compact busy periods with start, end, status, and subject fields.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the get_message MCP tool, which retrieves the full details of a single email message by ID via the Microsoft Graph API. The response includes all message fields: body content, all recipient fields (to, cc, bcc), internet message headers, and attachment metadata. Output modes (summary/raw) control the level of detail returned.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the list_accounts MCP tool, which returns all registered accounts in the account registry. For each authenticated account, the email address is lazily fetched from the Microsoft Graph /me endpoint and cached on the AccountEntry for use in subsequent tool confirmations.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the mail_list_attachments MCP tool, which lists attachment metadata (id, name, contentType, size, isInline) for a given message via the Microsoft Graph API. It exists because mail_get_message does not expose attachment IDs, leaving callers unable to subsequently invoke mail_get_attachment. This tool fills that gap with a lightweight enumeration endpoint that does not download attachment content.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the list_calendars MCP tool, which retrieves all calendars accessible to the authenticated user via the Microsoft Graph API. The tool returns a JSON array of calendar objects, each containing identification, display, and ownership metadata.

Package tools — this file implements the system.list_docs verb handler (CR-0061 Phase 2). It returns the catalog of embedded documentation documents with slug, title, summary, tags, and size.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the list_events MCP tool, which retrieves calendar events within a specified time range using the CalendarView endpoint. The CalendarView endpoint expands recurring events into individual occurrences, providing an accurate schedule representation. Pagination is handled via the Graph SDK's PageIterator with a configurable max_results cap.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the list_mail_folders MCP tool, which retrieves the authenticated user's mail folders via the Microsoft Graph API. The tool returns a JSON array of folder objects, each containing the folder ID, display name, unread item count, and total item count.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the list_messages MCP tool, which retrieves email messages from the authenticated user's mailbox via the Microsoft Graph API. The tool supports filtering by folder, date range, sender, and conversation ID using OData $filter. Results are ordered by receivedDateTime descending and support pagination via max_results. Output modes (summary/raw) control the level of detail returned.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the account_login MCP tool (CR-0056), which re-authenticates an existing disconnected account without removing and re-adding it. It reuses the inline authentication machinery from add_account.go (via addAccountState) to drive browser, device_code, or auth_code flows against the account's persisted client_id, tenant_id, and auth_method.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the account_logout MCP tool (CR-0056), which disconnects an authenticated account without removing it from the registry or accounts.json. The tool flips the entry's Authenticated flag to false, clears the in-memory credential/client handles, and clears the persisted token cache for the account's cache partition. The account remains visible in account_list and status as "disconnected" and can be re-authenticated via account_login.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides a shared helper for validating the output mode parameter on read tools. The output mode controls whether tool responses return a compact summary or the full raw Graph API serialization.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the account_refresh MCP tool (CR-0056), which forces a token refresh for an authenticated account. It calls GetToken on the account's persisted credential with policy.TokenRequestOptions (EnableCAE=true) so the credential returns a fresh, CAE-enabled access token. The new token expiry time is surfaced in the tool response (FR-27) so the LLM and user can confirm the refresh took effect.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the remove_account MCP tool, which removes a previously registered account from the account registry. Per CR-0056 FR-44/FR-45 the tool succeeds for any registered label regardless of connection state and leaves a clean zero-account state when the last account is removed.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the reschedule_event MCP tool, which moves an existing personal calendar event to a new time while preserving its original duration. The handler performs two Graph API calls: GET to retrieve the current event start/end, and PATCH to update with the new computed times. To reschedule an event that has attendees (sends update notifications), use calendar_reschedule_meeting instead.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the reschedule_meeting MCP tool definition, which moves an existing calendar meeting (event with attendees) to a new time while preserving its original duration. The tool reuses HandleRescheduleEvent for its handler logic; only the tool definition differs from reschedule_event. The description includes unconditional confirmation guidance warning about attendee update notifications.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the respond_event MCP tool, which responds to a meeting invitation on the authenticated user's calendar via the Microsoft Graph API. The tool supports three response types: accept, tentatively accept, and decline. An optional comment parameter allows the attendee to include a message to the organizer.

Package tools — this file implements the system.search_docs verb handler (CR-0061 Phase 2). It performs case-insensitive keyword search across the embedded documentation bundle and returns ranked results with slug, snippet, and 1-based line numbers.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the search_events MCP tool, which searches calendar events within a time range using optional OData filters and client-side substring matching. The tool builds a composite OData $filter string from the provided parameters (importance, sensitivity, is_all_day, show_as, is_cancelled) and applies case-insensitive substring matching on the subject field client-side. Categories filtering is also performed client-side.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the search_messages MCP tool, which performs full-text search across email messages using Microsoft Graph's KQL $search parameter. The tool supports optional folder scoping, pagination via max_results, and summary/raw output modes. Note: $search cannot be combined with $filter, and $orderby is restricted when $search is used (results are ranked by relevance).

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the pure query-normalisation seam for the search_messages tool. Microsoft Graph requires a message $search value to be enclosed in double quotes, and it rejects the double-quoted property phrase the tool's own description teaches. An unquoted multi-word query is worse than rejected: Graph accepts it, binds only the first token, and returns the newest unrelated messages as if they matched. This function converts a caller's query into a value Graph accepts while preserving the caller's intent, with no Graph dependency and no network call, so the quoting decision is testable without an account.

@agents-index: Pure normalisation of a search_messages KQL query into a Graph-accepted $search value, preserving caller intent.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the status MCP tool, a read-only diagnostic that returns a JSON summary of server health including version, timezone, per-account authentication state, uptime, and the full effective runtime configuration grouped into six categories. It makes no Graph API calls and completes within 100ms.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides plain-text formatters for the "text" output mode on read tools. Each formatter takes serialized data (maps from the graph serialization layer) and produces a human-readable plain-text string with numbered listings, formatted times, and summary totals.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the mail_update_draft MCP tool, which updates an existing draft message via PATCH /me/messages/{id} on the Microsoft Graph API. Only explicitly provided fields are set on the request body (PATCH semantics). The handler first GETs the message to verify isDraft=true and rejects updates on non-draft messages.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the update_event MCP tool, which modifies an existing personal calendar event (without attendee changes) via PATCH /me/events/{id} on the Microsoft Graph API. Only fields explicitly provided in the request are set on the request body, preserving PATCH semantics where omitted fields retain their current values. Supports converting events to/from Teams online meetings via is_online_meeting. To update attendees on an event, use calendar_update_meeting instead.

Package tools provides MCP tool definitions and handler constructors for the Outlook Calendar MCP Server.

This file provides the update_meeting MCP tool definition, which modifies an existing calendar meeting (event with attendees) via the Microsoft Graph API. The tool reuses HandleUpdateEvent for its handler logic; only the tool definition differs from update_event. The attendees parameter is present as optional (updates may modify other fields while attendees exist on the event), and the description includes unconditional confirmation guidance for attendee-affecting operations.

Index

Constants

View Source
const AccountParamDescription = "Account to use — accepts either the account label OR the User Principal Name (UPN, e.g., alice@contoso.com); lookup tries label first, then UPN. " +
	"Never assume a default account: inspect account_list (or the current account landscape) and consider every registered account, including disconnected ones, before acting. " +
	"Omitting this parameter yields silent auto-selection ONLY when exactly one account is authenticated and no other accounts (connected or disconnected) are registered. " +
	"When a single authenticated account coexists with disconnected accounts, auto-selection still occurs but the response surfaces an advisory naming the disconnected accounts — raise that advisory to the user rather than ignoring it. " +
	"In every other situation determine the account explicitly: ask the user or rely on prior context. " +
	"Use account_list to enumerate all registered accounts (authenticated and disconnected) with their UPNs."

AccountParamDescription is the shared description text applied to the `account` parameter of every tool that supports account selection (CR-0056 FR-42, FR-49, FR-50). The text is deliberately explicit about three things:

  1. Both the account label AND its User Principal Name (UPN, e.g., "alice@contoso.com") are accepted. The resolver performs label lookup first, then UPN fallback.
  2. Auto-selection is NOT a generic "default account" behavior. Omitting `account` only auto-selects when exactly one account is authenticated AND zero other accounts (connected or disconnected) are registered. When the single authenticated account coexists with disconnected siblings the resolver still auto-selects but emits an advisory so the LLM can surface the disconnected siblings to the user.
  3. The LLM must never silently assume a "default account" — it must inspect the current account landscape (via account_list or prior context), consider disconnected accounts, and ask the user when intent is ambiguous.

Variables

This section is empty.

Functions

func AccountInfoLine added in v0.2.1

func AccountInfoLine(ctx context.Context) string

AccountInfoLine returns a formatted "Account: label (email)" line from the AccountInfo stored in context by the AccountResolver middleware. The line is suitable for appending to write-tool confirmation responses. Returns an empty string when no AccountInfo is in context or the label is empty.

Parameters:

  • ctx: the request context containing the injected AccountInfo.

Returns a formatted account line, or "" when not available.

Side effects: none.

func AggregateAnnotations added in v0.5.0

func AggregateAnnotations(title string, verbs []Verb) []mcp.ToolOption

AggregateAnnotations computes the conservative aggregate MCP annotations for a domain tool from the set of verbs registered for that domain, returning them as the mcp.ToolOption slice mcp.NewTool expects.

The fold is conservative as defined in AGENTS.md and CR-0068 (FR-3..FR-6):

  • readOnlyHint is true only when EVERY registered verb is read-only.
  • destructiveHint is true when AT LEAST ONE registered verb is destructive.
  • idempotentHint is false when AT LEAST ONE registered verb is non-idempotent.
  • openWorldHint is true when AT LEAST ONE registered verb calls Graph.

title is the human-readable tool title carried through unchanged. verbs is the registered verb set; an empty slice yields the deterministic, maximally cautious default (readOnly false, destructive true, idempotent false, openWorld true) and never panics, so a degenerate registry cannot produce a misleadingly permissive annotation.

The function is pure: it performs no I/O and does not mutate its inputs, so tool registration remains synchronous and side-effect free (NFR-2).

func BuildDraftBody added in v0.3.0

func BuildDraftBody(content, contentType string) models.ItemBodyable

BuildDraftBody constructs a models.ItemBody from the body content and content_type parameters. content_type is case-insensitive and defaults to "text" when empty. "html" selects models.HTML_BODYTYPE; any other value has already been rejected by ValidateContentType.

Parameters:

  • content: the body string (plain text or HTML).
  • contentType: the content type string ("text" or "html"); empty defaults to "text".

Returns a configured ItemBody.

Side effects: none.

func BuildRecipients added in v0.3.0

func BuildRecipients(addrs []string) []models.Recipientable

BuildRecipients converts a slice of validated email address strings into a slice of models.Recipientable for the Graph SDK. Each recipient is constructed with its address set on a fresh EmailAddress, with no display name.

Parameters:

  • addrs: a slice of validated email address strings.

Returns the Recipientable slice, or nil when addrs is empty.

Side effects: none.

func FormatAboutText added in v0.5.0

func FormatAboutText(info buildinfo.Info) string

FormatAboutText formats a buildinfo.Info into a labelled single-screen plain-text rendering suitable for the LLM to read once and remember. The output stays under 24 lines as required by CR-0067 FR-9.

Parameters:

  • info: the buildinfo.Info snapshot from buildinfo.Snapshot.

Returns a formatted plain-text string.

Side effects: none.

func FormatAccountLine added in v0.2.1

func FormatAccountLine(label, email string, advisory ...string) string

FormatAccountLine returns a formatted "Account: label (upn)" line suitable for appending to write-tool confirmation responses. UPN is always included when non-empty (after CR-0056, UPN is persisted so it should almost always be available). An optional disconnected-account advisory is appended on a trailing line so the LLM raises the broader account landscape rather than silently operating on the auto-selected account (CR-0056 FR-52 / AC-17).

Parameters:

  • label: the account label (e.g., "default", "work").
  • email: the account email/UPN address; may be empty.
  • advisory: optional advisory text produced by the AccountResolver when auto-selection coexists with disconnected accounts. Empty when no advisory applies.

Returns a single- or two-line string, or the empty string when label is empty.

Side effects: none.

func FormatAccountsText

func FormatAccountsText(accounts []map[string]any) string

FormatAccountsText formats a slice of account maps into a numbered plain-text listing showing each account's label, User Principal Name (UPN) when available, authentication state, and auth_method (CR-0056).

Format: "N. label — upn (state, auth_method)". When the UPN is empty the em-dash and UPN portion are omitted; when auth_method is empty only the state is shown inside the parentheses.

Parameters:

  • accounts: slice of account maps, each expected to contain "label" (string), "authenticated" (bool), and optionally "email" (string) and "auth_method" (string) keys.

Returns a formatted plain-text string. Returns "No accounts registered." when the slice is nil or empty.

Side effects: none.

func FormatAttachmentText added in v0.3.0

func FormatAttachmentText(att map[string]any) string

FormatAttachmentText formats a serialized attachment map into a human-readable plain-text detail view showing name, content type, size, and an indicator that the content is delivered as base64 in summary/raw output modes.

Parameters:

  • att: a map produced by graph.SerializeAttachment.

Returns a formatted plain-text string.

Side effects: none.

func FormatAttachmentsText added in v0.3.0

func FormatAttachmentsText(atts []map[string]any) string

FormatAttachmentsText formats a slice of attachment metadata maps into a numbered plain-text listing showing id, name, content type, size, and inline flag. Used by mail_list_attachments.

Parameters:

  • atts: slice of attachment maps (from graph.SerializeSummaryAttachment or SerializeAttachment). Each is expected to contain "id", "name", "contentType", "size", and optionally "isInline".

Returns a formatted plain-text string. Returns "No attachments." when the slice is empty.

Side effects: none.

func FormatCalendarsText

func FormatCalendarsText(calendars []map[string]any) string

FormatCalendarsText formats a slice of serialized calendar maps into a numbered plain-text listing.

Parameters:

  • calendars: slice of calendar maps (from SerializeCalendar), each expected to contain "name", "owner", "isDefaultCalendar", and "canEdit" keys.

Returns a formatted plain-text string. Returns "No calendars found." when the slice is empty.

Side effects: none.

func FormatConversationText added in v0.3.0

func FormatConversationText(thread map[string]any) string

FormatConversationText formats a serialized conversation thread into a numbered plain-text listing ordered chronologically. Each entry shows the message subject, sender address, received date, and a body preview.

Parameters:

  • thread: a map produced by graph.SerializeConversationThread, expected to contain "conversationId", "count", and "messages" keys.

Returns a formatted plain-text string. Returns "No messages found." when the thread contains no messages.

Side effects: none.

func FormatDraftConfirmation added in v0.3.0

func FormatDraftConfirmation(action, subject, draftID string) string

FormatDraftConfirmation formats a concise plain-text confirmation for draft write operations. The output includes the action verb, subject (or "(No subject)" when empty), the draft ID, and a trailing line explaining that the draft is available in the user's Drafts folder and is not sent automatically.

Parameters:

  • action: the action verb (e.g., "created", "updated", "deleted").
  • subject: the draft subject/title. May be empty.
  • draftID: the Graph API message ID of the draft.

Returns a multi-line text confirmation.

Side effects: none.

func FormatEventDetailText

func FormatEventDetailText(event map[string]any) string

FormatEventDetailText formats a single serialized event map into a human-readable plain-text detail view. Includes subject, time, location, organizer, status, attendees, and body preview when available.

Parameters:

  • event: a summary-get event map (from SerializeSummaryGetEvent), expected to contain "subject", "displayTime", "location", "organizer", "showAs", "attendees", and "bodyPreview" keys.

Returns a formatted plain-text string.

Side effects: none.

func FormatEventsText

func FormatEventsText(events []map[string]any) string

FormatEventsText formats a slice of serialized summary event maps into a numbered plain-text listing with human-readable times and a total count. Each event shows subject, displayTime, location, showAs status, and organizer.

Parameters:

  • events: slice of summary event maps (from SerializeSummaryEvent or ToSummaryEventMap), each expected to contain "subject", "displayTime", "location", "showAs", and "organizer" keys.

Returns a formatted plain-text string. Returns "No events found." when the slice is empty.

Side effects: none.

func FormatFreeBusyText

func FormatFreeBusyText(data FreeBusyResponse) string

FormatFreeBusyText formats a FreeBusyResponse into a human-readable plain-text listing of busy periods.

Parameters:

  • data: a FreeBusyResponse struct containing timeRange and busyPeriods.

Returns a formatted plain-text string with a numbered list of busy periods. Returns "No busy periods found." when there are no busy periods.

Side effects: none.

func FormatMailFoldersText

func FormatMailFoldersText(folders []map[string]any) string

FormatMailFoldersText formats a slice of serialized mail folder maps into a numbered plain-text listing with unread and total item counts.

Parameters:

  • folders: slice of folder maps (from serializeMailFolder), each expected to contain "displayName", "unreadItemCount", and "totalItemCount" keys.

Returns a formatted plain-text string. Returns "No folders found." when the slice is nil or empty.

Side effects: none.

func FormatMessageDetailText

func FormatMessageDetailText(message map[string]any) string

FormatMessageDetailText formats a single serialized message map into a human-readable plain-text detail view. Includes subject, sender, recipients, date, importance (when not "normal"), attachment indicator, and body preview.

Parameters:

  • message: a message map (from SerializeSummaryMessage or SerializeMessage), expected to contain "subject", "from", "toRecipients", "receivedDateTime", "importance", "hasAttachments", and "bodyPreview" keys.

Returns a formatted plain-text string.

Side effects: none.

func FormatMessagesText

func FormatMessagesText(messages []map[string]any) string

FormatMessagesText formats a slice of serialized summary message maps into a numbered plain-text listing. Each message shows subject, sender address, date, read/attachment status flags, and body preview.

Parameters:

  • messages: slice of summary message maps (from SerializeSummaryMessage), each expected to contain "subject", "from" (map with "address"), "receivedDateTime", "isRead", "hasAttachments", and "bodyPreview" keys.

Returns a formatted plain-text string. Returns "No messages found." when the slice is nil or empty.

Side effects: none.

func FormatStatusText

func FormatStatusText(status statusResponse) string

FormatStatusText formats a statusResponse struct into a human-readable plain-text summary showing server version, timezone, uptime, account list with authentication state, and feature flags. This is the text-mode output for the status tool; full configuration is available via output=summary or output=raw.

Parameters:

  • status: the statusResponse struct from the status tool handler.

Returns a formatted plain-text string.

Side effects: none.

func FormatWriteConfirmation

func FormatWriteConfirmation(action, subject, eventID, displayTime, location string) string

FormatWriteConfirmation formats a concise text confirmation for write tool responses (create, update, reschedule). The output includes the action verb, subject, event ID, display time, and optionally the location.

Parameters:

  • action: the action verb (e.g., "created", "updated", "rescheduled").
  • subject: the event subject/title.
  • eventID: the Graph API event ID.
  • displayTime: the human-readable time range (e.g., "Wed Mar 25, 2:00 PM - 3:00 PM").
  • location: the event location. When empty, the Location line is omitted.

Returns a multi-line text confirmation that does not exceed 5 lines.

Side effects: none.

func GraphClient

func GraphClient(ctx context.Context) (*msgraphsdk.GraphServiceClient, error)

GraphClient retrieves the Microsoft Graph client from the request context. The AccountResolver middleware injects the client via auth.WithGraphClient before the handler runs. If the client is not in context (e.g., no account has been selected), an error is returned.

Parameters:

  • ctx: the request context containing the injected Graph client.

Returns the Graph client, or an error if the client is not present.

func HandleAbout added in v0.5.0

func HandleAbout(version, commit, buildDate string) func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleAbout returns a handler for the system.about verb. The handler is read-only, makes no Microsoft Graph call, and is safe to invoke without authentication.

Parameters:

  • version: the binary version string injected at build time.
  • commit: the short Git commit SHA injected at build time.
  • buildDate: the RFC3339 UTC build timestamp injected at build time.

The auth backend is read at request time from auth.ActiveBackend() so it reflects the resolved backend even when called early in startup.

Returns a handler compatible with the MCP server dispatch layer.

func HandleAddAccount

func HandleAddAccount(registry *auth.AccountRegistry, cfg config.Config) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleAddAccount creates a tool handler that adds a new account to the registry. The handler validates the label, creates a per-account credential, performs inline authentication using MCP Elicitation (URL mode for browser, form mode for device code), builds a Graph client, and registers the account.

Parameters:

  • registry: the account registry where the new account will be stored.
  • cfg: the server configuration providing default values for client_id, tenant_id, auth_method, cache_name, and auth_record_path.

Returns a tool handler function compatible with the MCP server's AddTool method. The handler returns a JSON success message with the account label, or an error result if validation, credential creation, authentication, or registration fails.

Side effects: creates a new credential with OS keychain cache partition, performs authentication (browser or device code), persists the auth record, registers the account in the registry.

func HandleCancelEvent

func HandleCancelEvent(retryCfg graph.RetryConfig, timeout time.Duration) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleCancelEvent is the MCP tool handler for cancel_meeting. It extracts the event_id and optional comment from the request arguments, builds the cancel request body, calls the Graph API POST /cancel endpoint, and returns a plain text confirmation on success. The Graph client is retrieved from the request context at invocation time.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.

Returns a closure matching the MCP tool handler function signature. The closure returns an *mcp.CallToolResult with either a plain text confirmation containing the event ID and a cancellation message, or an error result formatted via FormatGraphError when the Graph API call fails.

Side effects: calls POST /me/events/{id}/cancel on the Microsoft Graph API. Logs at debug level on entry, error level on failure, and info level on success.

func HandleCompleteAuth

func HandleCompleteAuth(cred auth.Authenticator, authRecordPath string, registry *auth.AccountRegistry, scopes []string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleCompleteAuth creates a tool handler that completes the auth code flow by exchanging the redirect URL for tokens. When an "account" parameter is provided, the handler looks up the account in the registry and uses its credential; otherwise it falls back to the default credential.

Parameters:

  • cred: the default account's Authenticator that must also implement auth.AuthCodeFlow.
  • authRecordPath: the filesystem path for persisting account metadata after successful token exchange (used for the default account).
  • registry: the account registry for looking up named accounts. May be nil when multi-account is not active.
  • scopes: OAuth scopes to request during token exchange (from auth.Scopes(cfg)).

Returns a tool handler function compatible with the MCP server's AddTool method. The handler returns a JSON success message via mcp.NewToolResultText, or an error result if the redirect URL is missing, the credential does not support auth_code, or the token exchange fails.

Side effects: exchanges the authorization code for tokens via MSAL, persists account metadata to disk on success.

func HandleCreateEvent

func HandleCreateEvent(retryCfg graph.RetryConfig, timeout time.Duration, defaultTimezone string, provenancePropertyID string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleCreateEvent is the MCP tool handler for create_event. It extracts parameters from the request, constructs a models.Event, calls the appropriate Graph API endpoint, and returns a concise text confirmation. The Graph client is retrieved from the request context at invocation time.

When provenancePropertyID is non-empty, the handler stamps a single-value extended property on the event before the POST call, tagging it as MCP-created. When empty, provenance tagging is skipped entirely.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.
  • defaultTimezone: the IANA timezone from server config, used as the default when start_timezone or end_timezone is omitted by the caller.
  • provenancePropertyID: the full MAPI property ID for provenance tagging, built once at startup via graph.BuildProvenancePropertyID. Empty string disables provenance tagging.

Returns a closure matching the MCP tool handler function signature.

Side effects: calls POST /me/events or POST /me/calendars/{id}/events on the Microsoft Graph API. Logs at debug level on entry, error level on failure, and info level on success.

func HandleDeleteEvent

func HandleDeleteEvent(retryCfg graph.RetryConfig, timeout time.Duration) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleDeleteEvent is the MCP tool handler for delete_event. It extracts the event_id from the request arguments, calls the Graph API DELETE endpoint, and returns a plain text confirmation on success. The Graph client is retrieved from the request context at invocation time.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.

Returns a closure matching the MCP tool handler function signature. The closure returns an *mcp.CallToolResult with either a plain text confirmation containing the event ID and a cancellation notice message, or an error result formatted via FormatGraphError when the Graph API call fails.

Side effects: calls DELETE /me/events/{id} on the Microsoft Graph API. Logs at debug level on entry, error level on failure, and info level on success.

func HandleGetDocs added in v0.4.0

func HandleGetDocs() func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleGetDocs returns a handler for the system.get_docs verb.

The handler reads the document identified by the required "slug" parameter from the embedded bundle. When "section" is provided it extracts the body of the matching H2 heading (case-insensitive anchor match). When "output" is "raw" the unmodified markdown is returned; the default "text" output strips leading/trailing whitespace.

Parameters extracted from the request:

  • slug (required): the document identifier (e.g., "troubleshooting").
  • section (optional): heading anchor to extract (e.g., "token-refresh").
  • output (optional): "text" (default) or "raw".

Returns mcp.NewToolResultError when the slug is not in the bundle or the section heading is not found. The error is returned as a tool result (not a Go error) so the LLM can read it.

func HandleListAccounts

func HandleListAccounts(registry *auth.AccountRegistry) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleListAccounts creates a tool handler that lists all registered accounts from the account registry. For each authenticated account, it calls EnsureEmail to lazily populate the email address from the Microsoft Graph /me endpoint. Each account is serialized as a JSON object with "label", "authenticated", and "email" fields.

Parameters:

  • registry: the account registry to query for registered accounts.

Returns a tool handler function compatible with the MCP server's AddTool method. The handler returns a JSON array of account objects via mcp.NewToolResultText, or an error result if JSON serialization fails.

Side effects: calls GET /me on the Graph API for each authenticated account whose email has not yet been fetched.

func HandleListDocs added in v0.4.0

func HandleListDocs() func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleListDocs returns a handler for the system.list_docs verb.

The handler reads the embedded documentation catalog via docs.Catalog and formats it according to the requested output tier (text default, raw JSON). No Graph API calls are made; the catalog is resolved from the embedded bundle at call time.

The response is a numbered plain-text list by default. When output="raw" the handler returns JSON. The "summary" mode is identical to "raw" for catalog output because all catalog fields are already curated.

Returns a CallToolResult or an error result when the catalog cannot be read (broken build).

func HandleLoginAccount added in v0.3.0

func HandleLoginAccount(registry *auth.AccountRegistry, cfg config.Config) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleLoginAccount creates a tool handler that re-authenticates an existing disconnected account. The handler looks up the entry by label, rejects already-connected accounts, constructs a credential from the persisted client_id / tenant_id / auth_method, attempts silent token acquisition first (CR-0064 Phase 3), and falls back to the same inline authentication flow used by add_account only when silent acquisition fails. It then builds a fresh Graph client and updates the registry entry atomically via registry.Update. On success it refreshes the UPN from /me and persists it to accounts.json.

Parameters:

  • registry: the account registry holding the target entry.
  • cfg: server configuration supplying scopes, cache base name, and the accounts.json path used for UPN persistence.

Returns a tool handler function compatible with the MCP server's AddTool method. The handler returns a JSON success message with the account label and refreshed UPN, or an error result if lookup, authentication, or Graph client creation fails.

Side effects: creates a new credential with the account's keychain cache partition, runs interactive authentication, mutates the registry entry (Credential, Authenticator, Client, CacheName, AuthRecordPath, Authenticated, Email), and may rewrite accounts.json to persist a resolved UPN.

func HandleLogoutAccount added in v0.3.0

func HandleLogoutAccount(registry *auth.AccountRegistry) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleLogoutAccount creates a tool handler that disconnects an authenticated account. The handler looks up the entry by label, rejects already-disconnected accounts, and atomically mutates the entry via registry.Update to clear Credential, Authenticator, and Client and to set Authenticated=false. It then clears the persisted token cache for the entry's CacheName via auth.ClearTokenCache. The registry entry and accounts.json are preserved so the account can be re-authenticated via account_login.

Parameters:

  • registry: the account registry holding the target entry.

Returns a tool handler function compatible with the MCP server's AddTool method. The handler returns a JSON success message with the account label on success, or an error result if lookup fails or the account is already disconnected.

Side effects: mutates the registry entry (Credential=nil, Authenticator=nil, Client=nil, Authenticated=false) and best-effort deletes the token cache artifacts for the account's CacheName.

func HandleRefreshAccount added in v0.3.0

func HandleRefreshAccount(registry *auth.AccountRegistry, cfg config.Config) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleRefreshAccount creates a tool handler that forces a token refresh for an authenticated account. The handler looks up the entry by label, rejects disconnected accounts, and calls GetToken on the entry's credential with a CAE-enabled policy.TokenRequestOptions so the underlying azidentity credential issues a fresh token. On success the new token expiry time (UTC, RFC3339) is included in the response payload.

Parameters:

  • registry: the account registry holding the target entry.
  • cfg: server configuration supplying the OAuth scope set used for the token request.

Returns a tool handler function compatible with the MCP server's AddTool method. The handler returns a plain-text confirmation naming the account (label and UPN when known) and the new token expiry on success, or an error result if lookup fails, the account is disconnected, or the credential rejects the token request.

Side effects: invokes the Microsoft identity platform via the credential's GetToken method. The underlying credential's token cache is updated with the refreshed token.

func HandleRemoveAccount

func HandleRemoveAccount(registry *auth.AccountRegistry, accountsPath string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleRemoveAccount creates a tool handler that removes an account from the account registry by label. After removing from the in-memory registry, it also removes the account's identity configuration from accounts.json. Per CR-0056 FR-44/FR-45 the handler succeeds regardless of the account's Authenticated state and leaves a valid zero-account state when the last account is removed; no label is protected from removal.

Parameters:

  • registry: the account registry from which the account will be removed.
  • accountsPath: the filesystem path to the persistent accounts.json file.

Returns a tool handler function compatible with the MCP server's AddTool method. The handler returns a plain-text confirmation naming the removed account (label plus UPN when known) via mcp.NewToolResultText, or an error result if the label is missing or does not refer to a registered account.

Side effects: removes the account entry from the registry and the persistent accounts file on success.

func HandleRescheduleEvent

func HandleRescheduleEvent(retryCfg graph.RetryConfig, timeout time.Duration, defaultTimezone string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleRescheduleEvent is the MCP tool handler for reschedule_event. It retrieves the existing event's start/end times via GET /me/events/{id}, computes the original duration, adds it to the new start time to produce the new end time, and updates the event via PATCH /me/events/{id}.

When new_start_timezone is omitted, the handler defaults to the server's configured default timezone.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for each Graph API call.
  • defaultTimezone: the IANA timezone from server config, used as the default when new_start_timezone is omitted.

Returns a closure matching the MCP tool handler function signature. The closure returns an *mcp.CallToolResult with either a text confirmation containing the rescheduled event details, or an error result when validation or Graph API calls fail.

Side effects: calls GET /me/events/{id} and PATCH /me/events/{id} on the Microsoft Graph API (at most 2 calls per invocation). Logs at debug level on entry, error level on failure, and info level on success.

func HandleRespondEvent

func HandleRespondEvent(retryCfg graph.RetryConfig, timeout time.Duration) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleRespondEvent is the MCP tool handler for respond_event. It extracts the event_id, response type, optional comment, and optional send_response from the request arguments, then routes to the correct Graph API endpoint based on the response value:

  • "accept" -> POST /me/events/{id}/accept
  • "tentative" -> POST /me/events/{id}/tentativelyAccept
  • "decline" -> POST /me/events/{id}/decline

Each endpoint accepts a request body with Comment (string) and SendResponse (boolean). When send_response is omitted, it defaults to true.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.

Returns a closure matching the MCP tool handler function signature. The closure returns an *mcp.CallToolResult with either a plain text confirmation containing the response action and event ID, or an error result when validation fails or the Graph API call fails.

Side effects: calls POST /me/events/{id}/{accept|tentativelyAccept|decline} on the Microsoft Graph API. Logs at debug level on entry, error level on failure, and info level on success.

func HandleSearchDocs added in v0.4.0

func HandleSearchDocs() func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleSearchDocs returns a handler for the system.search_docs verb.

The handler delegates to docs.Search using the required "query" parameter and formats the results as plain text by default. An empty query or a query that produces no results returns a structured zero-results response rather than an error, consistent with the body-escalation pattern in CLAUDE.md.

Parameters extracted from the request:

  • query (required): the search term to match across the bundle.
  • output (optional): "text" (default) or "raw"; "summary" behaves as "raw".

Returns a CallToolResult with ranked snippets.

func HandleStatus

func HandleStatus(cfg config.Config, registry *auth.AccountRegistry, startTime time.Time) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleStatus creates a tool handler that returns a JSON summary of server health including version, timezone, accounts, uptime, and the full effective runtime configuration. The handler captures its dependencies at construction time and makes no network calls, ensuring it completes within 100ms.

Parameters:

  • cfg: the server configuration struct containing all runtime settings.
  • registry: the account registry to query for account states.
  • startTime: the time the server started, used to compute uptime.

Returns a tool handler function compatible with the MCP server's AddTool method. The handler returns a JSON object via mcp.NewToolResultText, or an error result if JSON serialization fails.

Side effects: none. The handler only reads from the registry and computes elapsed time.

func HandleUpdateEvent

func HandleUpdateEvent(retryCfg graph.RetryConfig, timeout time.Duration, defaultTimezone string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

HandleUpdateEvent is the MCP tool handler for update_event. It extracts the event_id and only the provided optional fields, constructs a models.Event with PATCH semantics, calls PATCH /me/events/{id}, and returns a concise text confirmation. The Graph client is retrieved from the request context at invocation time.

When start_datetime or end_datetime is provided without a corresponding timezone, the handler defaults the timezone to the server's configured default timezone rather than returning an error.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.
  • defaultTimezone: the IANA timezone from server config, used as the default when start_timezone or end_timezone is omitted alongside a datetime update.

Returns a closure matching the MCP tool handler function signature.

Side effects: calls PATCH /me/events/{id} on the Microsoft Graph API. Logs at debug level on entry, error level on failure, and info level on success.

func MaybeSetMailProvenance added in v0.3.0

func MaybeSetMailProvenance(msg models.Messageable, propertyID string)

MaybeSetMailProvenance stamps the MCP provenance extended property on the given message when propertyID is non-empty. When propertyID is empty the call is a no-op, keeping provenance opt-in via the ProvenanceTag server config.

Parameters:

  • msg: a models.Messageable (typically a draft) on which to set the extended property.
  • propertyID: the full provenance property ID from graph.BuildProvenancePropertyID. Empty disables tagging.

Side effects: mutates msg by calling SetSingleValueExtendedProperties.

func NewAddAccountTool

func NewAddAccountTool() mcp.Tool

NewAddAccountTool creates the MCP tool definition for add_account. The tool accepts a required "label" parameter and optional "client_id", "tenant_id", and "auth_method" parameters for customizing the account's credential.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewCancelMeetingTool added in v0.2.1

func NewCancelMeetingTool() mcp.Tool

NewCancelMeetingTool creates the MCP tool definition for cancel_meeting. The tool accepts a required event_id and an optional comment string parameter. It does not carry a ReadOnlyHintAnnotation because it is a destructive write operation.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewCompleteAuthTool

func NewCompleteAuthTool() mcp.Tool

NewCompleteAuthTool creates the MCP tool definition for complete_auth. The tool accepts a required "redirect_url" string parameter (the full nativeclient redirect URL from the browser) and an optional "account" string parameter for multi-account scenarios (Phase 5).

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewCreateDraftTool added in v0.3.0

func NewCreateDraftTool() mcp.Tool

NewCreateDraftTool creates the MCP tool definition for mail_create_draft. All parameters are optional; when all are omitted, an empty draft is created. The draft appears in the user's Outlook Drafts folder and is not sent automatically.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewCreateEventTool

func NewCreateEventTool() mcp.Tool

NewCreateEventTool creates the MCP tool definition for create_event. The tool accepts required parameters for subject and start_datetime, plus optional parameters for start/end timezone (default to server's configured timezone), end_datetime (default to start + 30 minutes, or + 24 hours for all-day events), body, location, online meeting, all-day, importance, sensitivity, show_as, categories, recurrence, reminder_minutes, and calendar_id.

This tool does not accept attendees. To create an event with attendees, use calendar_create_meeting instead.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewCreateForwardDraftTool added in v0.3.0

func NewCreateForwardDraftTool() mcp.Tool

NewCreateForwardDraftTool creates the MCP tool definition for mail_create_forward_draft. It requires a message_id identifying the source message, and accepts optional to_recipients (comma-separated) and comment parameters.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewCreateMeetingTool added in v0.2.1

func NewCreateMeetingTool() mcp.Tool

NewCreateMeetingTool creates the MCP tool definition for calendar_create_meeting. The tool has the same parameters as NewCreateEventTool except the attendees parameter is required (not optional). The description includes unconditional confirmation guidance, CR-0039 body/location advisory, external domain warning, and AskUserQuestion reference.

The handler for this tool is HandleCreateEvent -- meeting tools reuse existing event handlers since the underlying Graph API calls are identical.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewCreateReplyDraftTool added in v0.3.0

func NewCreateReplyDraftTool() mcp.Tool

NewCreateReplyDraftTool creates the MCP tool definition for mail_create_reply_draft. It requires a message_id identifying the source message, and accepts an optional comment (prepended to the quoted original) and an optional reply_all boolean (default false).

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewDeleteDraftTool added in v0.3.0

func NewDeleteDraftTool() mcp.Tool

NewDeleteDraftTool creates the MCP tool definition for mail_delete_draft. It requires a message_id identifying the draft to remove. Destructive: deletion is permanent.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewDeleteEventTool

func NewDeleteEventTool() mcp.Tool

NewDeleteEventTool creates the MCP tool definition for delete_event. The tool accepts a required event_id string parameter. It does not carry a ReadOnlyHintAnnotation because it is a destructive write operation.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewGetAttachmentTool added in v0.3.0

func NewGetAttachmentTool() mcp.Tool

NewGetAttachmentTool creates the MCP tool definition for mail_get_attachment. The tool downloads a single attachment's metadata and base64 content.

Parameters:

  • message_id: required parent message ID.
  • attachment_id: required attachment ID.
  • account: optional account label for multi-account selection.
  • output: optional output mode (text/summary/raw).

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewGetConversationTool added in v0.3.0

func NewGetConversationTool() mcp.Tool

NewGetConversationTool creates the MCP tool definition for mail_get_conversation. The tool retrieves all messages in an email thread in chronological order (oldest first). Either a message_id (to resolve the conversationId) or a conversation_id may be supplied.

Parameters:

  • message_id: required unless conversation_id is supplied.
  • conversation_id: optional; when present, skips the initial message fetch.
  • max_results: optional maximum number of messages (default 50, max 100).
  • account: optional account label for multi-account selection.
  • output: optional output mode (text/summary/raw).

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewGetEventTool

func NewGetEventTool() mcp.Tool

NewGetEventTool creates the MCP tool definition for get_event. The tool accepts one required parameter (event_id) and two optional parameters (timezone, account). It is annotated as read-only since it only retrieves data.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewGetFreeBusyTool

func NewGetFreeBusyTool() mcp.Tool

NewGetFreeBusyTool creates the MCP tool definition for get_free_busy. It accepts start_datetime and end_datetime for fine-grained control, or a date convenience parameter that expands to start/end boundaries. When date is provided, start_datetime and end_datetime become optional. The tool is annotated as read-only since it only retrieves data.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewGetMessageTool

func NewGetMessageTool() mcp.Tool

NewGetMessageTool creates the MCP tool definition for get_message. The tool retrieves the full details of a single email message by its ID, including body content, all recipient fields, internet message headers, and attachment metadata. It is annotated as read-only since it only retrieves data from the Graph API without making any modifications.

Parameters:

  • message_id: required unique identifier of the message to retrieve.
  • account: optional account label for multi-account selection.
  • output: optional output mode (summary/raw).

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewHandleCreateDraft added in v0.3.0

func NewHandleCreateDraft(retryCfg graph.RetryConfig, timeout time.Duration, provenancePropertyID string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleCreateDraft creates the MCP tool handler for mail_create_draft. It validates optional recipient/body/importance parameters, constructs a models.Message, optionally stamps the MCP provenance extended property when provenancePropertyID is non-empty, and POSTs the message to /me/messages. The Graph API assigns a draft ID and stores the message in the Drafts folder without sending it.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.
  • provenancePropertyID: the full MAPI property ID for provenance tagging (built via graph.BuildProvenancePropertyID). Empty string disables provenance.

Returns a handler function compatible with the MCP server AddTool signature.

Side effects: calls POST /me/messages on the Microsoft Graph API. Logs at debug level on entry, error level on failure, and info level on success.

func NewHandleCreateForwardDraft added in v0.3.0

func NewHandleCreateForwardDraft(retryCfg graph.RetryConfig, timeout time.Duration, provenancePropertyID string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleCreateForwardDraft creates the MCP tool handler for mail_create_forward_draft. It calls the Graph SDK's createForward action with optional recipients and comment. When provenancePropertyID is non-empty, a follow-up PATCH stamps the provenance extended property on the returned draft.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for a single Graph API call.
  • provenancePropertyID: the full MAPI property ID for provenance tagging. Empty string disables the follow-up PATCH.

Returns a handler function compatible with the MCP server AddTool signature.

Side effects: calls POST /me/messages/{id}/createForward, and optionally PATCH /me/messages/{draftID} for provenance.

func NewHandleCreateReplyDraft added in v0.3.0

func NewHandleCreateReplyDraft(retryCfg graph.RetryConfig, timeout time.Duration, provenancePropertyID string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleCreateReplyDraft creates the MCP tool handler for mail_create_reply_draft. It routes to createReply or createReplyAll based on the reply_all flag. When provenancePropertyID is non-empty, a follow-up PATCH stamps the provenance extended property on the returned draft (Graph API does not support extended properties on the createReply request body directly).

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for a single Graph API call.
  • provenancePropertyID: the full MAPI property ID for provenance tagging. Empty string disables the follow-up PATCH.

Returns a handler function compatible with the MCP server AddTool signature.

Side effects: calls POST /me/messages/{id}/createReply or /createReplyAll, and optionally PATCH /me/messages/{draftID} for provenance.

func NewHandleDeleteDraft added in v0.3.0

func NewHandleDeleteDraft(retryCfg graph.RetryConfig, timeout time.Duration) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleDeleteDraft creates the MCP tool handler for mail_delete_draft. It verifies the target is a draft, then calls DELETE /me/messages/{id} on the Graph API.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for a single Graph API call.

Returns a handler function compatible with the MCP server AddTool signature.

Side effects: calls GET then DELETE /me/messages/{id} on the Microsoft Graph API.

func NewHandleGetAttachment added in v0.3.0

func NewHandleGetAttachment(retryCfg graph.RetryConfig, timeout time.Duration, maxSize int64) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleGetAttachment creates a tool handler that retrieves an attachment's metadata and base64-encoded content by calling GET /me/messages/{message_id}/attachments/{attachment_id} via the Graph SDK. The maxSize parameter enforces an upper bound on the attachment's reported size. Attachments exceeding the limit cause the handler to return an error without returning content.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.
  • maxSize: the maximum allowed attachment size in bytes. Values <=0 are treated as unlimited.

Returns a tool handler function compatible with the MCP server's AddTool method.

func NewHandleGetConversation added in v0.3.0

func NewHandleGetConversation(retryCfg graph.RetryConfig, timeout time.Duration, provenancePropertyID string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleGetConversation creates a tool handler that returns a full email conversation thread by calling GET /me/messages with a conversationId filter and chronological ordering.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for a single Graph API call.

Returns a tool handler function compatible with the MCP server's AddTool method.

The handler:

  • Retrieves the Graph client from context via GraphClient.
  • Requires either message_id or conversation_id; when only message_id is provided, fetches the message to resolve conversationId.
  • Queries /me/messages with $filter=conversationId eq '...' and $orderby=receivedDateTime asc.
  • Paginates with a max_results cap.
  • Serializes each message per the requested output mode and returns the thread via SerializeConversationThread.

func NewHandleGetEvent

func NewHandleGetEvent(retryCfg graph.RetryConfig, timeout time.Duration, defaultTimezone, provenancePropertyID string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleGetEvent creates a tool handler that retrieves full event details by ID by calling GET /me/events/{id} via the Graph SDK. The Graph client is retrieved from the request context at invocation time.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.
  • defaultTimezone: the IANA timezone name from server config used as the default when the caller omits the timezone parameter, matching calendar_list_events / calendar_search_events behavior.
  • provenancePropertyID: the full provenance property ID string, built once at startup. When non-empty, $expand is added to request the provenance extended property, and the serialized event includes "createdByMcp" when tagged.

Returns a tool handler function compatible with the MCP server's AddTool method.

The handler:

  • Retrieves the Graph client from context via GraphClient.
  • Extracts and validates the required event_id parameter.
  • Wraps the Graph API call with RetryGraphCall for transient error handling.
  • Applies a comprehensive $select and optional $expand covering all event fields.
  • Sets the Prefer header for timezone when provided.
  • Serializes the event including body, attendees, recurrence, and metadata.
  • Returns Graph API errors via mcp.NewToolResultError with FormatGraphError.
  • Logs entry at debug level, completion at info level, errors at error level.

func NewHandleGetFreeBusy

func NewHandleGetFreeBusy(retryCfg graph.RetryConfig, timeout time.Duration, defaultTimezone string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleGetFreeBusy creates a tool handler that retrieves busy periods within a time range by querying CalendarView and filtering out events with showAs equal to "free". The Graph client is retrieved from the request context at invocation time.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.
  • defaultTimezone: the IANA timezone name used to expand the date convenience parameter to start/end boundaries.

Returns a tool handler function compatible with the MCP server's AddTool method.

The handler:

  • Retrieves the Graph client from context via GraphClient.
  • Resolves the date convenience parameter to start_datetime/end_datetime when explicit values are not provided.
  • Validates that start_datetime and end_datetime are present (either explicit or expanded from date).
  • Queries CalendarView with pagination.
  • Filters out events where showAs equals "free".
  • Returns a JSON object with timeRange and busyPeriods fields.

func NewHandleGetMessage

func NewHandleGetMessage(retryCfg graph.RetryConfig, timeout time.Duration, provenancePropertyID string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleGetMessage creates a tool handler that retrieves full message details by ID by calling GET /me/messages/{id} via the Graph SDK. The Graph client is retrieved from the request context at invocation time.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.
  • provenancePropertyID: the full provenance property ID string, built once at startup. When non-empty, $expand is added to request the provenance extended property and each output mode includes a "provenance" boolean.

Returns a tool handler function compatible with the MCP server's AddTool method.

func NewHandleListAttachments added in v0.3.0

func NewHandleListAttachments(retryCfg graph.RetryConfig, timeout time.Duration) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleListAttachments creates a tool handler that lists attachment metadata for a message by calling GET /me/messages/{id}/attachments with a $select restricted to lightweight fields (no contentBytes).

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.

Returns a tool handler function compatible with the MCP server's AddTool method.

func NewHandleListCalendars

func NewHandleListCalendars(retryCfg graph.RetryConfig, timeout time.Duration) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleListCalendars creates a tool handler that lists all calendars for the authenticated user by calling GET /me/calendars via the Graph SDK. The Graph client is retrieved from the request context at invocation time.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.

Returns a tool handler function compatible with the MCP server's AddTool method.

The handler:

  • Retrieves the Graph client from context via GraphClient.
  • Applies a timeout context before the Graph API call.
  • Calls client.Me().Calendars().Get(ctx, nil) to retrieve all calendars.
  • Serializes each calendar into a map with keys: id, name, color, hexColor, isDefaultCalendar, canEdit, and owner (containing name and address).
  • Returns the JSON array via mcp.NewToolResultText.
  • Returns timeout errors via mcp.NewToolResultError with timeoutErrorMessage.
  • Returns Graph API errors via mcp.NewToolResultError with formatGraphError.
  • Logs entry at debug level, completion at info level with duration and count, and errors at error level.

func NewHandleListEvents

func NewHandleListEvents(retryCfg graph.RetryConfig, timeout time.Duration, defaultTimezone, provenancePropertyID string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleListEvents creates a tool handler that lists calendar events within a time range by calling the CalendarView endpoint via the Graph SDK. The Graph client is retrieved from the request context at invocation time.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.
  • defaultTimezone: the IANA timezone name used to expand the date convenience parameter to start/end-of-day boundaries.
  • provenancePropertyID: the full provenance property ID string, built once at startup. When non-empty, $expand is added to request the provenance extended property, and serialized events include "createdByMcp" when tagged.

Returns a tool handler function compatible with the MCP server's AddTool method.

The handler:

  • Retrieves the Graph client from context via GraphClient.
  • Resolves the date convenience parameter to start_datetime/end_datetime when explicit values are not provided.
  • Extracts and validates required parameters (start_datetime, end_datetime).
  • Routes to /me/calendarView or /me/calendars/{id}/calendarView based on calendar_id.
  • Applies $select, $orderby, $top, and $expand query parameters.
  • Sets the Prefer header for timezone when provided.
  • Uses PageIterator for pagination with a max_results cap.
  • Serializes events using SerializeEvent from the graph package.
  • Returns Graph API errors via mcp.NewToolResultError with FormatGraphError.
  • Logs entry at debug level, completion at info level, errors at error level.

func NewHandleListMailFolders

func NewHandleListMailFolders(retryCfg graph.RetryConfig, timeout time.Duration) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleListMailFolders creates a tool handler that lists mail folders for the authenticated user by calling GET /me/mailFolders via the Graph SDK. The Graph client is retrieved from the request context at invocation time.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.

Returns a tool handler function compatible with the MCP server's AddTool method.

The handler:

  • Retrieves the Graph client from context via GraphClient.
  • Applies a timeout context before the Graph API call.
  • Calls client.Me().MailFolders().Get(ctx, cfg) with $top and $select.
  • Serializes each folder into a map with keys: id, displayName, unreadItemCount, and totalItemCount.
  • Returns the JSON array via mcp.NewToolResultText.
  • Returns timeout errors via mcp.NewToolResultError with TimeoutErrorMessage.
  • Returns Graph API errors via mcp.NewToolResultError with RedactGraphError.
  • Logs entry at debug level, completion at info level with duration and count, and errors at error level.

func NewHandleListMessages

func NewHandleListMessages(retryCfg graph.RetryConfig, timeout time.Duration, provenancePropertyID string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleListMessages creates a tool handler that lists email messages by calling the Graph API's messages endpoint with OData $filter support. The Graph client is retrieved from the request context at invocation time.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.

Returns a tool handler function compatible with the MCP server's AddTool method.

The handler:

  • Retrieves the Graph client from context via GraphClient.
  • Validates optional parameters (folder_id, start_datetime, end_datetime, from, conversation_id, timezone).
  • Builds an OData $filter string from provided filter parameters, ANDing multiple conditions together.
  • Routes to /me/messages or /me/mailFolders/{id}/messages based on folder_id.
  • Orders results by receivedDateTime desc.
  • Uses PageIterator for pagination with a max_results cap.
  • Serializes messages using SerializeSummaryMessage or SerializeMessage from the graph package depending on the output mode.
  • Returns Graph API errors via mcp.NewToolResultError with RedactGraphError.
  • Returns timeout errors via mcp.NewToolResultError with TimeoutErrorMessage.
  • Logs entry at debug level, completion at info level, errors at error level.

func NewHandleSearchEvents

func NewHandleSearchEvents(retryCfg graph.RetryConfig, timeout time.Duration, defaultTimezone, provenancePropertyID string) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleSearchEvents creates a tool handler that searches calendar events using the CalendarView endpoint with composite OData filtering and client-side fallback logic. The Graph client is retrieved from the request context at invocation time.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.
  • defaultTimezone: the IANA timezone name used to expand the date convenience parameter to start/end boundaries.
  • provenancePropertyID: the full provenance property ID string, built once at startup. When non-empty, $expand is added to request the provenance extended property, and serialized events include "createdByMcp" when tagged.

Returns a tool handler function compatible with the MCP server's AddTool method.

The handler:

  • Retrieves the Graph client from context via GraphClient.
  • Resolves the date convenience parameter to start_datetime/end_datetime when explicit values are not provided.
  • Defaults start_datetime to now and end_datetime to 30 days from start when neither date nor explicit datetimes are provided.
  • Builds a composite OData $filter from importance, sensitivity, is_all_day, show_as, and is_cancelled (subject matching is always client-side).
  • Applies client-side case-insensitive substring matching on subject when query parameter is provided.
  • Applies client-side category filtering when categories parameter is provided.
  • Limits results to max_results.
  • Serializes events using SerializeEvent and returns a JSON array.

func NewHandleSearchMessages

func NewHandleSearchMessages(retryCfg graph.RetryConfig, timeout time.Duration) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleSearchMessages creates a tool handler that searches email messages by calling the Graph API's messages endpoint with the $search parameter. The Graph client is retrieved from the request context at invocation time.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for the Graph API call.

Returns a tool handler function compatible with the MCP server's AddTool method.

The handler:

  • Retrieves the Graph client from context via GraphClient.
  • Validates the required query parameter (returns error when empty).
  • Normalises the query via NormaliseSearchQuery once, before the folder branch and before any Graph call, so both request paths send an identical $search value and an unconvertible query is refused (with the error in both the tool result and the log) rather than reaching Graph.
  • Routes to /me/messages or /me/mailFolders/{id}/messages based on folder_id.
  • Sets $search with the normalised KQL query string.
  • Does NOT use $filter or $orderby (incompatible with $search).
  • Uses PageIterator for pagination with a max_results cap.
  • Serializes messages using SerializeSummaryMessage or SerializeMessage from the graph package depending on the output mode.
  • Returns Graph API errors via mcp.NewToolResultError with RedactGraphError.
  • Returns timeout errors via mcp.NewToolResultError with TimeoutErrorMessage.
  • Logs entry at debug level, completion at info level, errors at error level.

func NewHandleUpdateDraft added in v0.3.0

func NewHandleUpdateDraft(retryCfg graph.RetryConfig, timeout time.Duration) func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

NewHandleUpdateDraft creates the MCP tool handler for mail_update_draft. It first GETs the target message with a narrow $select to verify isDraft=true, then PATCHes the message with only explicitly provided fields.

Parameters:

  • retryCfg: retry configuration for transient Graph API errors.
  • timeout: the maximum duration for a single Graph API call.

Returns a handler function compatible with the MCP server AddTool signature.

Side effects: calls GET /me/messages/{id} then PATCH /me/messages/{id} on the Microsoft Graph API.

func NewListAccountsTool

func NewListAccountsTool() mcp.Tool

NewListAccountsTool creates the MCP tool definition for list_accounts. The tool takes no parameters and is annotated as read-only since it only reads from the in-memory account registry without side effects.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewListAttachmentsTool added in v0.3.0

func NewListAttachmentsTool() mcp.Tool

NewListAttachmentsTool creates the MCP tool definition for mail_list_attachments. The tool enumerates attachment metadata for a single message without downloading any content bytes, enabling callers to discover attachment IDs needed by mail_get_attachment.

Parameters:

  • message_id: required parent message ID.
  • account: optional account label for multi-account selection.
  • output: optional output mode (text/summary/raw).

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewListCalendarsTool

func NewListCalendarsTool() mcp.Tool

NewListCalendarsTool creates the MCP tool definition for list_calendars. The tool accepts an optional account parameter for multi-account selection and is annotated as read-only since it only retrieves data from the Graph API without making any modifications.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewListEventsTool

func NewListEventsTool() mcp.Tool

NewListEventsTool creates the MCP tool definition for list_events. The tool accepts an optional date convenience parameter that expands to start/end of day, plus explicit start_datetime/end_datetime for fine-grained control. When date is provided, start_datetime and end_datetime are derived automatically. When both are provided, explicit values take precedence.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewListMailFoldersTool

func NewListMailFoldersTool() mcp.Tool

NewListMailFoldersTool creates the MCP tool definition for list_mail_folders. The tool accepts an optional account parameter for multi-account selection and an optional max_results parameter (default 25) to limit the number of folders returned. It is annotated as read-only since it only retrieves data from the Graph API without making any modifications.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewListMessagesTool

func NewListMessagesTool() mcp.Tool

NewListMessagesTool creates the MCP tool definition for list_messages. The tool lists messages in a specific mail folder or across all folders, with OData $filter support for date ranges, sender filtering, and conversation threading. It is annotated as read-only since it only retrieves data from the Graph API without making any modifications.

Parameters:

  • folder_id: optional mail folder ID to scope the query.
  • start_datetime: optional start of date range filter (ISO 8601).
  • end_datetime: optional end of date range filter (ISO 8601).
  • from: optional sender email address filter.
  • conversation_id: optional conversation ID for thread retrieval.
  • max_results: optional maximum number of messages (default 25, max 100).
  • timezone: optional IANA timezone for the Prefer header.
  • account: optional account label for multi-account selection.
  • output: optional output mode (summary/raw).

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewLoginAccountTool added in v0.3.0

func NewLoginAccountTool() mcp.Tool

NewLoginAccountTool creates the MCP tool definition for account_login. The tool accepts a required "label" parameter identifying a previously registered but currently disconnected account. Annotations (CR-0052): ReadOnly=false, Destructive=false, Idempotent=false (a fresh authentication state is produced each invocation), OpenWorld=true (calls Microsoft identity and Graph APIs).

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewLogoutAccountTool added in v0.3.0

func NewLogoutAccountTool() mcp.Tool

NewLogoutAccountTool creates the MCP tool definition for account_logout. The tool accepts a required "label" parameter identifying a currently authenticated account. Annotations (CR-0052): ReadOnly=false (it mutates registry state), Destructive=false (configuration is preserved and logout is reversible via account_login), Idempotent=true (repeat calls on an already-disconnected account are rejected with the same deterministic error), OpenWorld=false (the handler is local-only: no Graph or identity API calls).

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewRefreshAccountTool added in v0.3.0

func NewRefreshAccountTool() mcp.Tool

NewRefreshAccountTool creates the MCP tool definition for account_refresh. The tool accepts a required "label" parameter identifying a currently authenticated account. Annotations (CR-0052): ReadOnly=false (refreshes the cached token state), Destructive=false (no data is removed and the account remains connected), Idempotent=true (repeat calls on the same account with the same arguments consistently produce a refreshed access token with an updated expiry), OpenWorld=true (the handler calls Microsoft identity to obtain a new token).

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewRemoveAccountTool

func NewRemoveAccountTool() mcp.Tool

NewRemoveAccountTool creates the MCP tool definition for remove_account. The tool accepts a required "label" parameter identifying the account to remove. It is not annotated as read-only since it mutates the registry.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewRescheduleEventTool

func NewRescheduleEventTool() mcp.Tool

NewRescheduleEventTool creates the MCP tool definition for reschedule_event. The tool accepts a required event_id and new_start_datetime, plus optional new_start_timezone (defaults to server config) and optional account selector. It preserves the original event duration, computing the new end time automatically.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewRescheduleMeetingTool added in v0.2.1

func NewRescheduleMeetingTool() mcp.Tool

NewRescheduleMeetingTool creates the MCP tool definition for calendar_reschedule_meeting. The tool has the same parameters as NewRescheduleEventTool. The description includes unconditional confirmation guidance referencing attendee notifications and AskUserQuestion reference.

The handler for this tool is HandleRescheduleEvent -- meeting tools reuse existing event handlers since the underlying Graph API calls are identical.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewRespondEventTool

func NewRespondEventTool() mcp.Tool

NewRespondEventTool creates the MCP tool definition for respond_event. The tool accepts a required event_id, a required response type (accept, tentative, or decline), an optional comment string, an optional send_response boolean (defaults to true), and an optional account selector.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewSearchEventsTool

func NewSearchEventsTool(provenanceEnabled bool) mcp.Tool

NewSearchEventsTool creates the MCP tool definition for search_events. All parameters are optional. The tool is annotated as read-only since it only retrieves data.

When provenanceEnabled is true, an additional optional created_by_mcp boolean parameter is registered, allowing callers to filter results to only MCP-created events using a server-side OData filter on the provenance extended property.

Parameters:

  • provenanceEnabled: whether provenance tagging is active. When false, the created_by_mcp parameter is not included in the tool definition.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewStatusTool

func NewStatusTool() mcp.Tool

NewStatusTool creates the MCP tool definition for the status diagnostic tool. The tool takes no required parameters and is annotated as read-only since it only inspects in-memory state without side effects or network calls.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewUpdateDraftTool added in v0.3.0

func NewUpdateDraftTool() mcp.Tool

NewUpdateDraftTool creates the MCP tool definition for mail_update_draft. It requires a message_id and accepts optional recipient, subject, body, content_type, and importance parameters. Only explicitly provided fields are updated.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewUpdateEventTool

func NewUpdateEventTool() mcp.Tool

NewUpdateEventTool creates the MCP tool definition for update_event. The tool accepts a required event_id and optional fields for mutable event properties, including Teams online meeting toggling. Only specified fields are changed (PATCH semantics).

This tool does not accept attendees. To update attendees on an event, use calendar_update_meeting instead.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NewUpdateMeetingTool added in v0.2.1

func NewUpdateMeetingTool() mcp.Tool

NewUpdateMeetingTool creates the MCP tool definition for calendar_update_meeting. The tool has the same parameters as NewUpdateEventTool. The attendees parameter remains optional because updates may modify other fields while attendees exist on the event. The description includes unconditional confirmation guidance, CR-0039 body/location advisory, external domain warning, and AskUserQuestion reference.

The handler for this tool is HandleUpdateEvent -- meeting tools reuse existing event handlers since the underlying Graph API calls are identical.

Returns the configured mcp.Tool ready for registration with server.AddTool.

func NormaliseSearchQuery added in v0.6.0

func NormaliseSearchQuery(query string) (string, error)

NormaliseSearchQuery converts a caller's search_messages query into a value Microsoft Graph accepts as a message $search value, preserving the caller's intent rather than merely producing something legal.

The four behaviours are applied in this order:

  1. Translate a property value delimited by double quotes into the parenthesised form: subject:"Design Review" becomes subject:(Design Review). The parenthesised form scopes to the property; the double-quoted form is rejected by Graph.
  2. Pass through unchanged a query already enclosed in one matched pair of double quotes with no remaining interior double quote, so a caller who found the hand-quoted workaround keeps working.
  3. Wrap a query carrying no double quote in exactly one enclosing pair, so a multi-word query filters rather than being silently discarded.
  4. Reject a double quote that neither delimits a property value nor forms the single enclosing pair, before any Graph call, returning an error that names the parenthesised form as the correction.

Deleting a quoted property value's inner quotes is deliberately not a behaviour: it always yields a legal expression but binds only the first token to the property and turns the rest into free-text terms, a silent wrong answer worse than an error.

The function is deterministic and idempotent: normalising an already- normalised query returns it unchanged.

It returns the normalised query and a nil error on success, or an empty string and an actionable error when the query cannot be translated.

func SerializeCalendar

func SerializeCalendar(cal models.Calendarable) map[string]any

SerializeCalendar converts a models.Calendarable into a map[string]any suitable for JSON serialization in MCP tool responses. All pointer fields are accessed through SafeStr and SafeBool helpers to prevent nil dereference panics.

Parameters:

  • cal: a models.Calendarable representing a calendar from the Microsoft Graph API.

Returns a map containing keys: id, name, color, hexColor, isDefaultCalendar, canEdit, and owner (with name and address sub-keys). The color field is extracted from the CalendarColor enum via its String() method.

Side effects: none.

func ValidateOutputMode

func ValidateOutputMode(request mcp.CallToolRequest) (string, error)

ValidateOutputMode extracts and validates the output parameter from an MCP tool request. Returns "text" (the default when the parameter is missing or empty), "summary", or "raw". Returns an error for any other value.

Parameters:

  • request: the MCP tool call request containing optional arguments.

Returns the validated output mode string, or an error if the value is not "text", "summary", "raw", or empty.

Side effects: none.

Types

type BusyPeriod

type BusyPeriod struct {
	// Start is the event start time in ISO 8601 format.
	Start string `json:"start"`
	// End is the event end time in ISO 8601 format.
	End string `json:"end"`
	// Status is the showAs value for the event (e.g., "busy", "tentative", "oof").
	Status string `json:"status"`
	// Subject is the event subject line.
	Subject string `json:"subject"`
	// DisplayTime is the localised, human-readable rendering of Start and End,
	// built with graph.FormatDisplayTime so that text output matches the
	// convention event listings already use. Start and End remain the raw ISO
	// 8601 values for machine consumers, so raw and summary output are
	// unchanged. Empty when Graph supplied no usable start or end.
	DisplayTime string `json:"displayTime,omitempty"`
}

BusyPeriod represents a single busy period in the free/busy response.

type DeviceCodeFallbackError

type DeviceCodeFallbackError struct {
	Message string
}

DeviceCodeFallbackError is returned when elicitation fails during device code authentication. It carries the device code message for the caller to return as a successful tool result, so the user sees the device code in the chat.

func (*DeviceCodeFallbackError) Error

func (e *DeviceCodeFallbackError) Error() string

Error returns the device code fallback message.

type DomainToolConfig added in v0.4.0

type DomainToolConfig struct {
	// Domain is the MCP tool name (e.g., "calendar", "mail").
	Domain string

	// Intro is the one-sentence domain description used in the top-level
	// tool description.
	Intro string

	// Verbs is the ordered list of operations for this domain, including "help".
	Verbs []Verb

	// ToolAnnotations provides the five required MCP annotation ToolOptions for
	// the aggregate tool, computed conservatively across all verbs.
	ToolAnnotations []mcp.ToolOption

	// Middleware is an optional middleware factory applied to every verb handler.
	Middleware func(mcpserver.ToolHandlerFunc) mcpserver.ToolHandlerFunc
}

DomainToolConfig holds configuration for a single domain aggregate tool registration. It is the input to RegisterDomainTool.

Domain is the domain name, used as both the MCP tool name and the prefix in the fully qualified identity "{domain}.{operation}" logged by audit.

Intro is a one-sentence domain description prepended to the verb list in the top-level tool description (see AC-4 / FR-3).

Verbs is the ordered list of Verb descriptors for this domain. The order determines the operation enum order exposed to MCP clients. "help" MUST be the first entry when it is supported.

ToolAnnotations is the slice of mcp.ToolOption values providing the five required MCP annotations (title, readOnly, destructive, idempotent, openWorld) for the aggregate tool as a whole, computed conservatively across all verbs per AC-9 / FR-9.

Middleware is an optional middleware factory applied to every verb handler. When non-nil, each verb's Handler is wrapped via middleware before being called. The factory receives the raw handler and returns the wrapped handler. Pass nil to call verb handlers directly (useful in tests).

type Example added in v0.4.0

type Example struct {
	// Args is the argument map for this example invocation, excluding "operation".
	Args map[string]any

	// Comment describes what this example demonstrates.
	Comment string
}

Example represents a single illustrative invocation of a verb. It captures the argument map the caller would pass and an optional human-readable comment that explains what the example demonstrates.

Args holds the key/value pairs that form the operation's arguments (excluding the "operation" key itself, which is implicit). Values may be any JSON- compatible type: string, bool, number, or a nested structure.

Comment is a brief sentence describing what this invocation demonstrates. It is displayed in text and summary help output. An empty Comment is valid.

type FreeBusyResponse

type FreeBusyResponse struct {
	// TimeRange contains the queried start and end times.
	TimeRange FreeBusyTimeRange `json:"timeRange"`
	// BusyPeriods contains the list of events where showAs is not "free".
	BusyPeriods []BusyPeriod `json:"busyPeriods"`
}

FreeBusyResponse represents the JSON response structure for the get_free_busy tool. It contains the queried time range and an array of busy periods.

type FreeBusyTimeRange

type FreeBusyTimeRange struct {
	// Start is the start of the queried time range in ISO 8601 format.
	Start string `json:"start"`
	// End is the end of the queried time range in ISO 8601 format.
	End string `json:"end"`
}

FreeBusyTimeRange represents the queried time range in the free/busy response.

type Handler added in v0.4.0

type Handler func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error)

Handler is the function signature for an MCP tool handler. It matches the ToolHandlerFunc type used by the mcp-go server, accepting a context and a CallToolRequest and returning a result or an error.

type Verb added in v0.4.0

type Verb struct {
	// Name is the operation identifier without the domain prefix.
	Name string

	// Summary is a concise (≤80 char) human-readable description of the verb.
	Summary string

	// Description is the full prose explanation of the verb's purpose and
	// behaviour. MUST be non-empty for every registered verb (CR-0065 FR-9).
	Description string

	// Examples holds zero or more illustrative invocations for this verb.
	Examples []Example

	// SeeDocs holds zero or more documentation references in the form
	// "slug" or "slug#anchor" pointing into docs.Bundle (CR-0065 FR-11).
	SeeDocs []string

	// Handler is the MCP handler function invoked when this verb is dispatched.
	Handler Handler

	// Annotations holds the five MCP annotation ToolOption values for this
	// verb, used when computing conservative aggregate annotations.
	Annotations []mcp.ToolOption

	// Schema holds the parameter schema ToolOption values for this verb's
	// operation-specific inputs, used for unknown-parameter validation.
	Schema []mcp.ToolOption
	// contains filtered or unexported fields
}

Verb describes a single dispatchable operation within a domain aggregate tool. Each Verb is one entry in the operation enum exposed to MCP clients.

Name is the operation identifier (e.g., "list_events"). It MUST be unique within a domain's verb registry and MUST NOT include the domain prefix.

Summary is a concise, ≤80-character description of the operation. It is appended to the domain tool's top-level description and returned verbatim when help output is produced.

Description is a full prose explanation of the verb's purpose, behaviour, and important caveats. It MUST be non-empty for every registered verb (enforced by TestEveryVerbHasDescription). Unlike Summary, it may span multiple sentences and reference related verbs, output modes, or SeeDocs anchors.

Examples is an ordered slice of illustrative invocations. Each entry contains an argument map and an optional comment. Examples are rendered in all three help output tiers (text, summary, raw). The slice may be empty.

SeeDocs is an ordered slice of documentation references. Each entry is either a bare slug (e.g., "concepts") or a slug with an anchor (e.g., "concepts#output-tiers"). Every entry MUST resolve to a slug in docs.Bundle, and any anchor MUST match an H2 heading in that file (enforced by TestSeeDocsAnchorsResolve). The slice may be empty.

Handler is the underlying MCP handler function that executes the operation. The dispatcher calls this function after routing the incoming request.

Annotations is a slice of mcp.ToolOption values that carry the five required MCP annotations (title, readOnly, destructive, idempotent, openWorld) for this verb. These are recorded in the Verb registry so that the dispatcher can compute conservative aggregate annotations across all verbs in a domain.

Schema is a slice of mcp.ToolOption values that define the JSON Schema properties for this verb's operation-specific parameters (e.g., mcp.WithString, mcp.Required). The dispatcher validates unknown parameter names against this list before invoking the handler.

type VerbRegistry added in v0.4.0

type VerbRegistry map[string]Verb

VerbRegistry maps operation names to their Verb descriptors for a single domain aggregate tool. It is populated by RegisterDomainTool and read by the dispatcher on every invocation.

func RegisterDomainTool added in v0.4.0

func RegisterDomainTool(s *mcpserver.MCPServer, cfg DomainToolConfig) VerbRegistry

RegisterDomainTool registers a single domain aggregate MCP tool on the given server. It performs three actions:

  1. Builds the `operation` enum from the registered verb names.
  2. Composes the top-level description listing every verb with its summary.
  3. Registers one mcp.Tool on the server whose handler routes calls to the correct Verb.Handler based on the `operation` argument.

The returned VerbRegistry may be used by callers (e.g., help renderers, tests) to inspect the registered verbs after registration.

Per FR-11, an unknown `operation` value returns a structured error listing valid verbs and suggesting `operation="help"`. Per FR-12, unknown parameters for a known verb are rejected with an error naming the parameter and verb.

Parameters:

  • s: the MCP server instance on which the tool is registered.
  • cfg: configuration for the domain tool, including domain name, intro, verbs, aggregate annotations, and an optional middleware factory.

Returns the populated VerbRegistry for the domain.

Side effects: registers one MCP tool on s and applies cfg.Middleware (if non-nil) to each verb handler.

Directories

Path Synopsis
Package help — this file contains shared helpers used by all three tier renderers (CR-0060 Phase 2).
Package help — this file contains shared helpers used by all three tier renderers (CR-0060 Phase 2).

Jump to

Keyboard shortcuts

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