toolsdk

package
v2.38.2 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: AGPL-3.0 Imports: 25 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	PromptNameAgentsDelegate = "coder_agents_delegate"
	PromptNameAgentsCheck    = "coder_agents_check"
)
View Source
const (
	ToolNameReportTask                  = "coder_report_task"
	ToolNameGetWorkspace                = "coder_get_workspace"
	ToolNameCreateWorkspace             = "coder_create_workspace"
	ToolNameListWorkspaces              = "coder_list_workspaces"
	ToolNameListOrganizations           = "coder_list_organizations"
	ToolNameListTemplates               = "coder_list_templates"
	ToolNameListTemplateVersionParams   = "coder_template_version_parameters"
	ToolNameGetTemplate                 = "coder_get_template"
	ToolNameGetAuthenticatedUser        = "coder_get_authenticated_user"
	ToolNameCreateWorkspaceBuild        = "coder_create_workspace_build"
	ToolNameCreateTemplateVersion       = "coder_create_template_version"
	ToolNameGetWorkspaceAgentLogs       = "coder_get_workspace_agent_logs"
	ToolNameGetWorkspaceBuildLogs       = "coder_get_workspace_build_logs"
	ToolNameGetTemplateVersionLogs      = "coder_get_template_version_logs"
	ToolNameUpdateTemplateActiveVersion = "coder_update_template_active_version"
	ToolNameUploadTarFile               = "coder_upload_tar_file"
	ToolNameCreateTemplate              = "coder_create_template"
	ToolNameDeleteTemplate              = "coder_delete_template"
	ToolNameWorkspaceBash               = "coder_workspace_bash"
	ToolNameChatGPTSearch               = "search"
	ToolNameChatGPTFetch                = "fetch"
	ToolNameWorkspaceLS                 = "coder_workspace_ls"
	ToolNameWorkspaceReadFile           = "coder_workspace_read_file"
	ToolNameWorkspaceWriteFile          = "coder_workspace_write_file"
	ToolNameWorkspaceEditFile           = "coder_workspace_edit_file"
	ToolNameWorkspaceEditFiles          = "coder_workspace_edit_files"
	ToolNameWorkspacePortForward        = "coder_workspace_port_forward"
	ToolNameWorkspaceListApps           = "coder_workspace_list_apps"
	ToolNameCreateChat                  = "coder_create_chat"
	ToolNameGetChat                     = "coder_get_chat"
	ToolNameDownloadChatFile            = "coder_download_chat_file"
	ToolNameAwaitChat                   = "coder_await_chat"
	ToolNameListChats                   = "coder_list_chats"
	ToolNameGetChatMessages             = "coder_get_chat_messages"
	ToolNameSendChatMessage             = "coder_send_chat_message"
	ToolNameInterruptChat               = "coder_interrupt_chat"
	ToolNameArchiveChat                 = "coder_archive_chat"
	ToolNameListChatModelConfigs        = "coder_list_chat_model_configs"
)

Tool name constants to avoid hardcoded strings

Variables

View Source
var AgentsCheck = Prompt{
	Name:        PromptNameAgentsCheck,
	Description: "Check the status and recent activity of an existing Coder Agents chat.",
	RequiredTools: []string{
		ToolNameGetChat,
		ToolNameGetChatMessages,
	},
	Arguments: []PromptArgument{
		{
			Name:        "chat_id",
			Description: "UUID of the Coder Agents chat to check.",
			Required:    true,
		},
	},
	Render: func(args map[string]string) (string, error) {
		chatID, err := requiredPromptArg(args, "chat_id")
		if err != nil {
			return "", err
		}
		return fmt.Sprintf(`Check on the Coder Agents chat %q and report back.

Follow these steps:
1. Call %s with the chat_id to get its status, last turn summary, and any last error.
2. Call %s with the chat_id for recent transcript context, including queued_messages.
3. Summarize for the user: what the agent is doing or has done, whether it is blocked or waiting for input, and any errors. Include the chat URL.
`, chatID, ToolNameGetChat, ToolNameGetChatMessages), nil
	},
}
View Source
var AgentsDelegate = Prompt{
	Name:        PromptNameAgentsDelegate,
	Description: "Delegate a coding task to a Coder Agents chat and monitor it to completion.",
	RequiredTools: []string{
		ToolNameCreateChat,
		ToolNameGetChat,
		ToolNameGetChatMessages,
		ToolNameSendChatMessage,
	},
	Arguments: []PromptArgument{
		{
			Name:        "task",
			Description: "The task the Coder Agent should perform, including all context it needs.",
			Required:    true,
		},
		{
			Name:        "organization_id",
			Description: "Organization UUID.",
		},
		{
			Name:        "model_config_id",
			Description: "Optional model config UUID for the chat. When omitted, the server uses an applicable personal override or the organization's default model.",
		},
	},
	Render: func(args map[string]string) (string, error) {
		task, err := requiredPromptArg(args, "task")
		if err != nil {
			return "", err
		}
		createStep := fmt.Sprintf("1. Call %s with the task above as the prompt", ToolNameCreateChat)
		organizationID := strings.TrimSpace(args["organization_id"])
		if organizationID != "" {
			createStep += fmt.Sprintf(" and organization_id %q", organizationID)
		}
		if modelConfigID := strings.TrimSpace(args["model_config_id"]); modelConfigID != "" {
			createStep += fmt.Sprintf(" and model_config_id %q.", modelConfigID)
		} else {
			createStep += fmt.Sprintf(". Omit model_config_id to let the server use an applicable personal override or the organization's default model. Only call %s if you want to select a specific model; pass the selected organization's ID to that tool.", ToolNameListChatModelConfigs)
		}
		if organizationID == "" {
			createStep += fmt.Sprintf(" Organization selection defaults only when you belong to exactly one organization. Otherwise, use %s to obtain organization IDs and details, select the intended organization with the user, and pass organization_id to chat creation and any model discovery call. A model config ID does not select an organization. If discovery is unavailable, ask the user for the organization ID.", ToolNameListOrganizations)
		}

		return fmt.Sprintf(`Delegate the following task to a Coder Agent and see it through to completion.

<task>
%s
</task>

Follow these steps:
%s
2. Share the returned chat URL with the user right away so they can follow along.
3. Poll %s until the chat stops running, waiting between polls.
4. Read the transcript with %s; page older history with before_id while has_more is true.
5. If the agent needs input or the result needs iteration, reply with %s and keep monitoring.
6. Report the outcome to the user, including the chat URL and a summary of what the agent did.
`, task, createStep, ToolNameGetChat, ToolNameGetChatMessages, ToolNameSendChatMessage), nil
	},
}
View Source
var All = []GenericTool{
	CreateTemplate.Generic(),
	CreateTemplateVersion.Generic(),
	CreateWorkspace.Generic(),
	CreateWorkspaceBuild.Generic(),
	DeleteTemplate.Generic(),
	ListOrganizations.Generic(),
	ListTemplates.Generic(),
	ListTemplateVersionParameters.Generic(),
	GetTemplate.Generic(),
	ListWorkspaces.Generic(),
	GetAuthenticatedUser.Generic(),
	GetTemplateVersionLogs.Generic(),
	GetWorkspace.Generic(),
	GetWorkspaceAgentLogs.Generic(),
	GetWorkspaceBuildLogs.Generic(),
	ReportTask.Generic(),
	UploadTarFile.Generic(),
	UpdateTemplateActiveVersion.Generic(),
	WorkspaceBash.Generic(),
	ChatGPTSearch.Generic(),
	ChatGPTFetch.Generic(),
	WorkspaceLS.Generic(),
	WorkspaceReadFile.Generic(),
	WorkspaceWriteFile.Generic(),
	WorkspaceEditFile.Generic(),
	WorkspaceEditFiles.Generic(),
	WorkspacePortForward.Generic(),
	WorkspaceListApps.Generic(),
	CreateChat.Generic(),
	GetChat.Generic(),
	DownloadChatFile.Generic(),
	AwaitChat.Generic(),
	ListChats.Generic(),
	GetChatMessages.Generic(),
	SendChatMessage.Generic(),
	InterruptChat.Generic(),
	ArchiveChat.Generic(),
	ListChatModelConfigs.Generic(),
}

All is a list of all tools that can be used in the Coder CLI. When you add a new tool, be sure to include it here!

AllPrompts is the canonical list of MCP prompts exposed by Coder MCP servers.

View Source
var ArchiveChat = Tool[ArchiveChatArgs, codersdk.Response]{
	Tool: aisdk.Tool{
		Name:        ToolNameArchiveChat,
		Description: `Archive a Coder Agents chat. The chat is hidden from default listings but can be unarchived from the UI.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"chat_id": map[string]any{
					"type":        "string",
					"description": chatIDDescription,
				},
			},
			Required: []string{"chat_id"},
		},
	},
	MCPAnnotations: mcpMutationAnnotations,
	Handler: func(ctx context.Context, deps Deps, args ArchiveChatArgs) (codersdk.Response, error) {
		chatID, err := parseChatID(args.ChatID)
		if err != nil {
			return codersdk.Response{}, err
		}
		archived := true
		err = codersdk.NewExperimentalClient(deps.coderClient).UpdateChat(ctx, chatID, codersdk.UpdateChatRequest{
			Archived: &archived,
		})
		if err != nil {
			return codersdk.Response{}, xerrors.Errorf("archive chat: %w", err)
		}
		return codersdk.Response{
			Message: "Chat archived successfully.",
		}, nil
	},
}
View Source
var AwaitChat = Tool[AwaitChatArgs, AwaitChatResponse]{
	Tool: aisdk.Tool{
		Name:        ToolNameAwaitChat,
		Description: `Block until a Coder Agents chat stops generating or the wait times out. Waiting, error, and requires_action all end the wait. If timed_out is true, chat holds the last status observed inside the wait window; call this tool again to continue waiting.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"chat_id": map[string]any{
					"type":        "string",
					"description": chatIDDescription,
				},
				"wait_secs": map[string]any{
					"type":        "integer",
					"description": "Maximum seconds to wait (1-120, default 60).",
				},
			},
			Required: []string{"chat_id"},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args AwaitChatArgs) (AwaitChatResponse, error) {
		chatID, err := parseChatID(args.ChatID)
		if err != nil {
			return AwaitChatResponse{}, err
		}
		if args.WaitSecs < 0 || args.WaitSecs > 120 {
			return AwaitChatResponse{}, xerrors.New("wait_secs must be between 1 and 120")
		}
		waitSecs := args.WaitSecs
		if waitSecs == 0 {
			waitSecs = 60
		}

		expClient := codersdk.NewExperimentalClient(deps.coderClient)

		waitCtx, cancelWait := context.WithTimeout(ctx, time.Duration(waitSecs)*time.Second)
		defer cancelWait()

		// lastBusy is the most recent (busy) chat state observed inside
		// the wait window; non-busy states return immediately instead.
		var lastBusy *codersdk.Chat

		finalStatus := func() (AwaitChatResponse, error) {
			if ctx.Err() != nil {
				return AwaitChatResponse{}, ctx.Err()
			}
			return AwaitChatResponse{TimedOut: true, Chat: chatToolStatus(deps, *lastBusy)}, nil
		}

		// Dial asynchronously: a slow or failed watch dial (e.g. a proxy
		// stalling or rejecting upgrades) must not block the REST poller.
		// The events channel stays nil until the dial succeeds; a missed
		// transition in that window is caught by the next poll tick.
		type watchDial struct {
			events <-chan codersdk.ChatWatchEvent
			closer io.Closer
		}
		dialed := make(chan watchDial, 1)
		go func() {
			events, closer, err := expClient.WatchChats(waitCtx)
			if err != nil {
				return
			}
			dialed <- watchDial{events: events, closer: closer}
		}()
		var (
			events      <-chan codersdk.ChatWatchEvent
			watchCloser io.Closer
		)
		defer func() {
			cancelWait()
			if watchCloser == nil {
				select {
				case dial := <-dialed:
					watchCloser = dial.closer
				default:
				}
			}
			if watchCloser != nil {
				_ = watchCloser.Close()
			}
		}()

		chat, err := expClient.GetChat(waitCtx, chatID)
		if err != nil {
			return AwaitChatResponse{}, xerrors.Errorf("get chat: %w", err)
		}
		if !chatStatusBusy(chat.Status) {
			return AwaitChatResponse{Chat: chatToolStatus(deps, chat)}, nil
		}
		lastBusy = &chat

		poller := time.NewTicker(5 * time.Second)
		defer poller.Stop()
		for {
			select {
			case <-waitCtx.Done():
				return finalStatus()
			case <-poller.C:
				chat, err := expClient.GetChat(waitCtx, chatID)
				if err != nil {
					if waitCtx.Err() != nil {
						return finalStatus()
					}
					return AwaitChatResponse{}, xerrors.Errorf("get chat while polling: %w", err)
				}
				if !chatStatusBusy(chat.Status) {
					return AwaitChatResponse{Chat: chatToolStatus(deps, chat)}, nil
				}
				lastBusy = &chat
			case dial := <-dialed:
				events = dial.events
				watchCloser = dial.closer
				dialed = nil
			case event, ok := <-events:
				if !ok {

					events = nil
					continue
				}
				if event.Chat.ID == chatID && !chatStatusBusy(event.Chat.Status) {
					chat, err := expClient.GetChat(waitCtx, chatID)
					if err != nil {
						if waitCtx.Err() != nil {
							return finalStatus()
						}
						return AwaitChatResponse{}, xerrors.Errorf("get chat after status change: %w", err)
					}

					if !chatStatusBusy(chat.Status) {
						return AwaitChatResponse{Chat: chatToolStatus(deps, chat)}, nil
					}
					lastBusy = &chat
				}
			}
		}
	},
}
View Source
var ChatGPTFetch = Tool[FetchArgs, FetchResult]{
	Tool: aisdk.Tool{
		Name: ToolNameChatGPTFetch,
		Description: `Fetch a template or workspace.

		ID is a unique identifier for the template or workspace. It is a combination of the type and the ID.

		# Examples

		Fetch a template with ID "56f13b5e-be0f-4a17-bdb2-aaacc3353ea7".

		` + "```" + `json
		{
			"id": "template:56f13b5e-be0f-4a17-bdb2-aaacc3353ea7"
		}
		` + "```" + `

		Fetch a workspace with ID "fcb6fc42-ba88-4175-9508-88e6a554a61a".

		` + "```" + `json
		{
			"id": "workspace:fcb6fc42-ba88-4175-9508-88e6a554a61a"
		}
		` + "```" + `
		`,

		Schema: aisdk.Schema{
			Properties: map[string]any{
				"id": map[string]any{
					"type": "string",
				},
			},
			Required: []string{"id"},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args FetchArgs) (FetchResult, error) {
		objectID, err := parseObjectID(args.ID)
		if err != nil {
			return FetchResult{}, err
		}
		switch objectID.Type {
		case ObjectTypeTemplate:
			return fetchTemplate(ctx, deps, objectID.ID)
		case ObjectTypeWorkspace:
			return fetchWorkspace(ctx, deps, objectID.ID)
		}
		return FetchResult{}, xerrors.Errorf("reached unreachable code with object ID: %s", args.ID)
	},
}

Implements the "fetch" tool as described in https://platform.openai.com/docs/mcp#fetch-tool. From my experiments with ChatGPT, it seems that it does not see the description that is provided in the tool definition. ChatGPT sees "fetch" as a very simple tool that can take an ID returned by the "search" tool and return the full details of the object.

View Source
var ChatGPTSearch = Tool[SearchArgs, SearchResult]{
	Tool: aisdk.Tool{
		Name: ToolNameChatGPTSearch,

		Description: `Search for templates, workspaces, and files in workspaces.

To pick what you want to search for, use the following query formats:

- ` + "`" + `templates/<template-query>` + "`" + `: List templates. The query accepts the following, optional parameters delineated by whitespace:
	- "name:<name>" - Fuzzy search by template name (substring matching). Example: "name:docker"
	- "organization:<organization>" - Filter by organization ID or name. Example: "organization:coder"
	- "deprecated:<true|false>" - Filter by deprecated status. Example: "deprecated:true"
	- "deleted:<true|false>" - Filter by deleted status. Example: "deleted:true"
- ` + "`" + `workspaces/<workspace-query>` + "`" + `: List workspaces. The query accepts the following, optional parameters delineated by whitespace:
	- "owner:<username>" - Filter by workspace owner (username or "me"). Example: "owner:alice" or "owner:me"
	- "template:<template-name>" - Filter by template name. Example: "template:web-development"
	- "name:<workspace-name>" - Filter by workspace name (substring matching). Example: "name:project"
	- "organization:<organization>" - Filter by organization ID or name. Example: "organization:engineering"
	- "status:<status>" - Filter by workspace/build status. Values: starting, stopping, deleting, deleted, stopped, started, running, pending, canceling, canceled, failed. Example: "status:running"
	- "has-agent:<agent-status>" - Filter by agent connectivity status. Values: connecting, connected, disconnected, timeout. Example: "has-agent:connected"
	- "dormant:<true|false>" - Filter dormant workspaces. Example: "dormant:true"
	- "outdated:<true|false>" - Filter workspaces using outdated template versions. Example: "outdated:true"
	- "last_used_after:<timestamp>" - Filter workspaces last used after a specific date. Example: "last_used_after:2023-12-01T00:00:00Z"
	- "last_used_before:<timestamp>" - Filter workspaces last used before a specific date. Example: "last_used_before:2023-12-31T23:59:59Z"
	- "param:<name>" or "param:<name>=<value>" - Match workspaces by build parameters. Example: "param:environment=production" or "param:gpu"

# Examples

## Listing templates

List all templates without any filters.

` + "```" + `json
{
	"query": "templates"
}
` + "```" + `

List all templates with a "docker" substring in the name.

` + "```" + `json
{
	"query": "templates/name:docker"
}
` + "```" + `

List templates in a specific organization.

` + "```" + `json
{
	"query": "templates/organization:engineering"
}
` + "```" + `

List deprecated templates.

` + "```" + `json
{
	"query": "templates/deprecated:true"
}
` + "```" + `

List templates with multiple filters - non-deprecated templates with "web" in the name.

` + "```" + `json
{
	"query": "templates/name:web deprecated:false"
}
` + "```" + `

List deleted templates (requires appropriate permissions).

` + "```" + `json
{
	"query": "templates/deleted:true"
}
` + "```" + `

## Listing workspaces

List all workspaces belonging to the current user.

` + "```" + `json
{
	"query": "workspaces/owner:me"
}
` + "```" + `

or 

` + "```" + `json
{
	"query": "workspaces"
}
` + "```" + `

List all workspaces belonging to a user with username "josh".

` + "```" + `json
{
	"query": "workspaces/owner:josh"
}
` + "```" + `

List all running workspaces.

` + "```" + `json
{
	"query": "workspaces/status:running"
}
` + "```" + `

List workspaces using a specific template.

` + "```" + `json
{
	"query": "workspaces/template:web-development"
}
` + "```" + `

List dormant workspaces.

` + "```" + `json
{
	"query": "workspaces/dormant:true"
}
` + "```" + `

List workspaces with connected agents.

` + "```" + `json
{
	"query": "workspaces/has-agent:connected"
}
` + "```" + `

List workspaces with multiple filters - running workspaces owned by "alice".

` + "```" + `json
{
	"query": "workspaces/owner:alice status:running"
}
` + "```" + `
`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"query": map[string]any{
					"type": "string",
				},
			},
			Required: []string{"query"},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args SearchArgs) (SearchResult, error) {
		query, err := parseSearchQuery(args.Query)
		if err != nil {
			return SearchResult{}, err
		}
		switch query.Type {
		case SearchQueryTypeTemplates:
			results, err := searchTemplates(ctx, deps, query.Query)
			if err != nil {
				return SearchResult{}, err
			}
			return SearchResult{Results: results}, nil
		case SearchQueryTypeWorkspaces:
			searchQuery := query.Query
			if searchQuery == "" {
				searchQuery = "owner:me"
			}
			results, err := searchWorkspaces(ctx, deps, searchQuery)
			if err != nil {
				return SearchResult{}, err
			}
			return SearchResult{Results: results}, nil
		}
		return SearchResult{}, xerrors.Errorf("reached unreachable code with query: %s", args.Query)
	},
}

Implements the "search" tool as described in https://platform.openai.com/docs/mcp#search-tool. From my experiments with ChatGPT, it has access to the description that is provided in the tool definition. This is in contrast to the "fetch" tool, where ChatGPT does not have access to the description.

View Source
var CreateChat = Tool[CreateChatArgs, ChatToolStatus]{
	Tool: aisdk.Tool{
		Name: ToolNameCreateChat,
		Description: `Start a Coder Agents chat: a server-side AI coding agent that works autonomously from a prompt.

The chat runs asynchronously. Poll coder_get_chat for status and read the transcript with coder_get_chat_messages.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"prompt": map[string]any{
					"type":        "string",
					"description": "Initial prompt for the agent.",
				},
				"organization_id": map[string]any{
					"type":        "string",
					"description": "Organization UUID.",
				},
				"owner_id": map[string]any{
					"type":        "string",
					"description": "Optional UUID of the user who owns the chat. Defaults to you. The chat runs with the owner's credentials, so creating it for another user requires site-wide owner authority. The owner must be an active member of the chat's organization; pass organization_id explicitly when it differs from your default.",
				},
				"model_config_id": map[string]any{
					"type":        "string",
					"description": "Optional chat model config UUID from coder_list_chat_model_configs. Must belong to the chat's organization. When omitted, the server uses an applicable personal override or the organization's default model.",
				},
				"labels": map[string]any{
					"type":                 "object",
					"description":          "Optional string key/value labels to attach to the chat.",
					"additionalProperties": map[string]any{"type": "string"},
				},
			},
			Required: []string{"prompt"},
		},
	},
	MCPAnnotations: mcpMutationAnnotations,
	Handler: func(ctx context.Context, deps Deps, args CreateChatArgs) (ChatToolStatus, error) {
		if args.Prompt == "" {
			return ChatToolStatus{}, xerrors.New("prompt is required")
		}
		orgID, err := resolveOrganization(ctx, deps, args.OrganizationID)
		if err != nil {
			return ChatToolStatus{}, err
		}
		var ownerID *uuid.UUID
		if args.OwnerID != "" {
			id, err := uuid.Parse(args.OwnerID)
			if err != nil {
				return ChatToolStatus{}, xerrors.New("owner_id must be a valid UUID")
			}
			if id == uuid.Nil {
				return ChatToolStatus{}, xerrors.New("owner_id must be a valid nonzero UUID")
			}
			ownerID = &id
		}
		var modelConfigID *uuid.UUID
		if args.ModelConfigID != "" {
			id, err := uuid.Parse(args.ModelConfigID)
			if err != nil {
				return ChatToolStatus{}, xerrors.New("model_config_id must be a valid UUID")
			}
			modelConfigID = &id
		}
		chat, err := codersdk.NewExperimentalClient(deps.coderClient).CreateChat(ctx, codersdk.CreateChatRequest{
			OrganizationID: orgID,
			OwnerID:        ownerID,
			Content: []codersdk.ChatInputPart{{
				Type: codersdk.ChatInputPartTypeText,
				Text: args.Prompt,
			}},
			ModelConfigID: modelConfigID,
			Labels:        args.Labels,
		})
		if err != nil {
			return ChatToolStatus{}, xerrors.Errorf("create chat: %w", err)
		}
		return chatToolStatus(deps, chat), nil
	},
}
View Source
var CreateTemplate = Tool[CreateTemplateArgs, codersdk.Template]{
	Tool: aisdk.Tool{
		Name:        ToolNameCreateTemplate,
		Description: "Create a new template in Coder. First, you must create a template version.",
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"organization_id": map[string]any{
					"type":        "string",
					"description": "Organization UUID.",
				},
				"name": map[string]any{
					"type": "string",
				},
				"display_name": map[string]any{
					"type": "string",
				},
				"description": map[string]any{
					"type": "string",
				},
				"icon": map[string]any{
					"type":        "string",
					"description": "A URL to an icon to use.",
				},
				"version_id": map[string]any{
					"type":        "string",
					"description": "The ID of the version to use.",
				},
			},
			Required: []string{"name", "display_name", "description", "version_id"},
		},
	},
	MCPAnnotations: mcpMutationAnnotations,
	Handler: func(ctx context.Context, deps Deps, args CreateTemplateArgs) (codersdk.Template, error) {
		organizationID, err := resolveOrganization(ctx, deps, args.OrganizationID)
		if err != nil {
			return codersdk.Template{}, err
		}
		versionID, err := uuid.Parse(args.VersionID)
		if err != nil {
			return codersdk.Template{}, xerrors.Errorf("version_id must be a valid UUID: %w", err)
		}
		template, err := deps.coderClient.CreateTemplate(ctx, organizationID, codersdk.CreateTemplateRequest{
			Name:        args.Name,
			DisplayName: args.DisplayName,
			Description: args.Description,
			VersionID:   versionID,
		})
		if err != nil {
			return codersdk.Template{}, err
		}
		return template, nil
	},
}
View Source
var CreateTemplateVersion = Tool[CreateTemplateVersionArgs, codersdk.TemplateVersion]{
	Tool: aisdk.Tool{
		Name: ToolNameCreateTemplateVersion,
		Description: `Create a new template version. This is a precursor to creating a template, or you can update an existing template.

Templates are Terraform defining a development environment. The provisioned infrastructure must run
an Agent that connects to the Coder Control Plane to provide a rich experience.

Here are some strict rules for creating a template version:
- YOU MUST NOT use "variable" or "output" blocks in the Terraform code.
- YOU MUST ALWAYS check template version logs after creation to ensure the template was imported successfully.

When a template version is created, a Terraform Plan occurs that ensures the infrastructure
_could_ be provisioned, but actual provisioning occurs when a workspace is created.

<terraform-spec>
The Coder Terraform Provider can be imported like:

` + "```" + `hcl
terraform {
  required_providers {
    coder = {
      source = "coder/coder"
    }
  }
}
` + "```" + `

A destroy does not occur when a user stops a workspace, but rather the transition changes:

` + "```" + `hcl
data "coder_workspace" "me" {}
` + "```" + `

This data source provides the following fields:
- id: The UUID of the workspace.
- name: The name of the workspace.
- transition: Either "start" or "stop".
- start_count: A computed count based on the transition field. If "start", this will be 1.

Access workspace owner information with:

` + "```" + `hcl
data "coder_workspace_owner" "me" {}
` + "```" + `

This data source provides the following fields:
- id: The UUID of the workspace owner.
- name: The name of the workspace owner.
- full_name: The full name of the workspace owner.
- email: The email of the workspace owner.
- session_token: A token that can be used to authenticate the workspace owner. It is regenerated every time the workspace is started.
- oidc_access_token: A valid OpenID Connect access token of the workspace owner. This is only available if the workspace owner authenticated with OpenID Connect. If a valid token cannot be obtained, this value will be an empty string.

Parameters are defined in the template version. They are rendered in the UI on the workspace creation page:

` + "```" + `hcl
resource "coder_parameter" "region" {
  name = "region"
  type = "string"
  default = "us-east-1"
}
` + "```" + `

This resource accepts the following properties:
- name: The name of the parameter.
- default: The default value of the parameter.
- type: The type of the parameter. Must be one of: "string", "number", "bool", or "list(string)".
- display_name: The displayed name of the parameter as it will appear in the UI.
- description: The description of the parameter as it will appear in the UI.
- ephemeral: The value of an ephemeral parameter will not be preserved between consecutive workspace builds.
- form_type: The type of this parameter. Must be one of: [radio, slider, input, dropdown, checkbox, switch, multi-select, tag-select, textarea, error].
- icon: A URL to an icon to display in the UI.
- mutable: Whether this value can be changed after workspace creation. This can be destructive for values like region, so use with caution!
- option: Each option block defines a value for a user to select from. (see below for nested schema)
  Required:
  - name: The name of the option.
  - value: The value of the option.
  Optional:
  - description: The description of the option as it will appear in the UI.
  - icon: A URL to an icon to display in the UI.

A Workspace Agent runs on provisioned infrastructure to provide access to the workspace:

` + "```" + `hcl
resource "coder_agent" "dev" {
  arch = "amd64"
  os = "linux"
}
` + "```" + `

This resource accepts the following properties:
- arch: The architecture of the agent. Must be one of: "amd64", "arm64", or "armv7".
- os: The operating system of the agent. Must be one of: "linux", "windows", or "darwin".
- auth: The authentication method for the agent. Must be one of: "token", "google-instance-identity", "aws-instance-identity", or "azure-instance-identity". It is insecure to pass the agent token via exposed variables to Virtual Machines. Instance Identity enables provisioned VMs to authenticate by instance ID on start.
- dir: The starting directory when a user creates a shell session. Defaults to "$HOME".
- env: A map of environment variables to set for the agent.
- startup_script: A script to run after the agent starts. This script MUST exit eventually to signal that startup has completed. Use "&" or "screen" to run processes in the background.

This resource provides the following fields:
- id: The UUID of the agent.
- init_script: The script to run on provisioned infrastructure to fetch and start the agent.
- token: Set the environment variable CODER_AGENT_TOKEN to this value to authenticate the agent.

The agent MUST be installed and started using the init_script. A utility like curl or wget to fetch the agent binary must exist in the provisioned infrastructure.

Expose terminal or HTTP applications running in a workspace with:

` + "```" + `hcl
resource "coder_app" "dev" {
  agent_id = coder_agent.dev.id
  slug = "my-app-name"
  display_name = "My App"
  icon = "https://my-app.com/icon.svg"
  url = "http://127.0.0.1:3000"
}
` + "```" + `

This resource accepts the following properties:
- agent_id: The ID of the agent to attach the app to.
- slug: The slug of the app.
- display_name: The displayed name of the app as it will appear in the UI.
- icon: A URL to an icon to display in the UI.
- url: An external url if external=true or a URL to be proxied to from inside the workspace. This should be of the form http://localhost:PORT[/SUBPATH]. Either command or url may be specified, but not both.
- command: A command to run in a terminal opening this app. In the web, this will open in a new tab. In the CLI, this will SSH and execute the command. Either command or url may be specified, but not both.
- external: Whether this app is an external app. If true, the url will be opened in a new tab.
</terraform-spec>

The Coder Server may not be authenticated with the infrastructure provider a user requests. In this scenario,
the user will need to provide credentials to the Coder Server before the workspace can be provisioned.

Here are examples of provisioning the Coder Agent on specific infrastructure providers:

<aws-ec2-instance>
// The agent is configured with "aws-instance-identity" auth.
terraform {
  required_providers {
    cloudinit = {
      source = "hashicorp/cloudinit"
    }
    aws = {
      source = "hashicorp/aws"
    }
  }
}

data "cloudinit_config" "user_data" {
  gzip          = false
  base64_encode = false
  boundary = "//"
  part {
    filename     = "cloud-config.yaml"
    content_type = "text/cloud-config"

	// Here is the content of the cloud-config.yaml.tftpl file:
	// #cloud-config
	// cloud_final_modules:
	//   - [scripts-user, always]
	// hostname: ${hostname}
	// users:
	//   - name: ${linux_user}
	//     sudo: ALL=(ALL) NOPASSWD:ALL
	//     shell: /bin/bash
    content = templatefile("${path.module}/cloud-init/cloud-config.yaml.tftpl", {
      hostname   = local.hostname
      linux_user = local.linux_user
    })
  }

  part {
    filename     = "userdata.sh"
    content_type = "text/x-shellscript"

	// Here is the content of the userdata.sh.tftpl file:
	// #!/bin/bash
	// sudo -u '${linux_user}' sh -c '${init_script}'
    content = templatefile("${path.module}/cloud-init/userdata.sh.tftpl", {
      linux_user = local.linux_user

      init_script = try(coder_agent.dev[0].init_script, "")
    })
  }
}

resource "aws_instance" "dev" {
  ami               = data.aws_ami.ubuntu.id
  availability_zone = "${data.coder_parameter.region.value}a"
  instance_type     = data.coder_parameter.instance_type.value

  user_data = data.cloudinit_config.user_data.rendered
  tags = {
    Name = "coder-${data.coder_workspace_owner.me.name}-${data.coder_workspace.me.name}"
  }
  lifecycle {
    ignore_changes = [ami]
  }
}
</aws-ec2-instance>

<gcp-vm-instance>
// The agent is configured with "google-instance-identity" auth.
terraform {
  required_providers {
    google = {
      source = "hashicorp/google"
    }
  }
}

resource "google_compute_instance" "dev" {
  zone         = module.gcp_region.value
  count        = data.coder_workspace.me.start_count
  name         = "coder-${lower(data.coder_workspace_owner.me.name)}-${lower(data.coder_workspace.me.name)}-root"
  machine_type = "e2-medium"
  network_interface {
    network = "default"
    access_config {
      // Ephemeral public IP
    }
  }
  boot_disk {
    auto_delete = false
    source      = google_compute_disk.root.name
  }
  // In order to use google-instance-identity, a service account *must* be provided.
  service_account {
    email  = data.google_compute_default_service_account.default.email
    scopes = ["cloud-platform"]
  }
  # ONLY FOR WINDOWS:
  # metadata = {
  #   windows-startup-script-ps1 = coder_agent.main.init_script
  # }
  # The startup script runs as root with no $HOME environment set up, so instead of directly
  # running the agent init script, create a user (with a homedir, default shell and sudo
  # permissions) and execute the init script as that user.
  #
  # The agent MUST be started in here.
  metadata_startup_script = <<EOMETA
#!/usr/bin/env sh
set -eux

# If user does not exist, create it and set up passwordless sudo
if ! id -u "${local.linux_user}" >/dev/null 2>&1; then
  useradd -m -s /bin/bash "${local.linux_user}"
  echo "${local.linux_user} ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/coder-user
fi

exec sudo -u "${local.linux_user}" sh -c '${coder_agent.main.init_script}'
EOMETA
}
</gcp-vm-instance>

<azure-vm-instance>
// The agent is configured with "azure-instance-identity" auth.
terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
    }
    cloudinit = {
      source = "hashicorp/cloudinit"
    }
  }
}

data "cloudinit_config" "user_data" {
  gzip          = false
  base64_encode = true

  boundary = "//"

  part {
    filename     = "cloud-config.yaml"
    content_type = "text/cloud-config"

	// Here is the content of the cloud-config.yaml.tftpl file:
	// #cloud-config
	// cloud_final_modules:
	// - [scripts-user, always]
	// bootcmd:
	//   # work around https://github.com/hashicorp/terraform-provider-azurerm/issues/6117
	//   - until [ -e /dev/disk/azure/scsi1/lun10 ]; do sleep 1; done
	// device_aliases:
	//   homedir: /dev/disk/azure/scsi1/lun10
	// disk_setup:
	//   homedir:
	//     table_type: gpt
	//     layout: true
	// fs_setup:
	//   - label: coder_home
	//     filesystem: ext4
	//     device: homedir.1
	// mounts:
	//   - ["LABEL=coder_home", "/home/${username}"]
	// hostname: ${hostname}
	// users:
	//   - name: ${username}
	//     sudo: ["ALL=(ALL) NOPASSWD:ALL"]
	//     groups: sudo
	//     shell: /bin/bash
	// packages:
	//   - git
	// write_files:
	//   - path: /opt/coder/init
	//     permissions: "0755"
	//     encoding: b64
	//     content: ${init_script}
	//   - path: /etc/systemd/system/coder-agent.service
	//     permissions: "0644"
	//     content: |
	//       [Unit]
	//       Description=Coder Agent
	//       After=network-online.target
	//       Wants=network-online.target

	//       [Service]
	//       User=${username}
	//       ExecStart=/opt/coder/init
	//       Restart=always
	//       RestartSec=10
	//       TimeoutStopSec=90
	//       KillMode=process

	//       OOMScoreAdjust=-900
	//       SyslogIdentifier=coder-agent

	//       [Install]
	//       WantedBy=multi-user.target
	// runcmd:
	//   - chown ${username}:${username} /home/${username}
	//   - systemctl enable coder-agent
	//   - systemctl start coder-agent
    content = templatefile("${path.module}/cloud-init/cloud-config.yaml.tftpl", {
      username    = "coder" # Ensure this user/group does not exist in your VM image
      init_script = base64encode(coder_agent.main.init_script)
      hostname    = lower(data.coder_workspace.me.name)
    })
  }
}

resource "azurerm_linux_virtual_machine" "main" {
  count               = data.coder_workspace.me.start_count
  name                = "vm"
  resource_group_name = azurerm_resource_group.main.name
  location            = azurerm_resource_group.main.location
  size                = data.coder_parameter.instance_type.value
  // cloud-init overwrites this, so the value here doesn't matter
  admin_username = "adminuser"
  admin_ssh_key {
    public_key = tls_private_key.dummy.public_key_openssh
    username   = "adminuser"
  }

  network_interface_ids = [
    azurerm_network_interface.main.id,
  ]
  computer_name = lower(data.coder_workspace.me.name)
  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }
  source_image_reference {
    publisher = "Canonical"
    offer     = "0001-com-ubuntu-server-focal"
    sku       = "20_04-lts-gen2"
    version   = "latest"
  }
  user_data = data.cloudinit_config.user_data.rendered
}
</azure-vm-instance>

<docker-container>
terraform {
  required_providers {
    coder = {
      source = "kreuzwerker/docker"
    }
  }
}

// The agent is configured with "token" auth.

resource "docker_container" "workspace" {
  count = data.coder_workspace.me.start_count
  image = "codercom/enterprise-base:ubuntu"
  # Uses lower() to avoid Docker restriction on container names.
  name = "coder-${data.coder_workspace_owner.me.name}-${lower(data.coder_workspace.me.name)}"
  # Hostname makes the shell more user friendly: coder@my-workspace:~$
  hostname = data.coder_workspace.me.name
  # Use the docker gateway if the access URL is 127.0.0.1.
  entrypoint = ["sh", "-c", replace(coder_agent.main.init_script, "/localhost|127\\.0\\.0\\.1/", "host.docker.internal")]
  env        = ["CODER_AGENT_TOKEN=${coder_agent.main.token}"]
  host {
    host = "host.docker.internal"
    ip   = "host-gateway"
  }
  volumes {
    container_path = "/home/coder"
    volume_name    = docker_volume.home_volume.name
    read_only      = false
  }
}
</docker-container>

<kubernetes-pod>
// The agent is configured with "token" auth.

resource "kubernetes_deployment" "main" {
  count = data.coder_workspace.me.start_count
  depends_on = [
    kubernetes_persistent_volume_claim.home
  ]
  wait_for_rollout = false
  metadata {
    name      = "coder-${data.coder_workspace.me.id}"
  }

  spec {
    replicas = 1
    strategy {
      type = "Recreate"
    }

    template {
      spec {
        security_context {
          run_as_user     = 1000
          fs_group        = 1000
          run_as_non_root = true
        }

        container {
          name              = "dev"
          image             = "codercom/enterprise-base:ubuntu"
          image_pull_policy = "Always"
          command           = ["sh", "-c", coder_agent.main.init_script]
          security_context {
            run_as_user = "1000"
          }
          env {
            name  = "CODER_AGENT_TOKEN"
            value = coder_agent.main.token
          }
        }
      }
    }
  }
}
</kubernetes-pod>

The file_id provided is a reference to a tar file you have uploaded containing the Terraform.
`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"organization_id": map[string]any{
					"type":        "string",
					"description": "Organization UUID.",
				},
				"template_id": map[string]any{
					"type": "string",
				},
				"file_id": map[string]any{
					"type": "string",
				},
			},
			Required: []string{"file_id"},
		},
	},
	MCPAnnotations: mcpMutationAnnotations,
	Handler: func(ctx context.Context, deps Deps, args CreateTemplateVersionArgs) (codersdk.TemplateVersion, error) {
		organizationID, err := resolveOrganization(ctx, deps, args.OrganizationID)
		if err != nil {
			return codersdk.TemplateVersion{}, err
		}
		fileID, err := uuid.Parse(args.FileID)
		if err != nil {
			return codersdk.TemplateVersion{}, xerrors.Errorf("file_id must be a valid UUID: %w", err)
		}
		var templateID uuid.UUID
		if args.TemplateID != "" {
			tid, err := uuid.Parse(args.TemplateID)
			if err != nil {
				return codersdk.TemplateVersion{}, xerrors.Errorf("template_id must be a valid UUID: %w", err)
			}
			templateID = tid
		}
		templateVersion, err := deps.coderClient.CreateTemplateVersion(ctx, organizationID, codersdk.CreateTemplateVersionRequest{
			Message:       "Created by AI",
			StorageMethod: codersdk.ProvisionerStorageMethodFile,
			FileID:        fileID,
			Provisioner:   codersdk.ProvisionerTypeTerraform,
			TemplateID:    templateID,
		})
		if err != nil {
			return codersdk.TemplateVersion{}, err
		}
		return templateVersion, nil
	},
}
View Source
var CreateWorkspace = Tool[CreateWorkspaceArgs, codersdk.Workspace]{
	Tool: aisdk.Tool{
		Name: ToolNameCreateWorkspace,
		Description: `Create a new workspace in Coder.

If a user is asking to "test a template", they are typically referring
to creating a workspace from a template to ensure the infrastructure
is provisioned correctly and the agent can connect to the control plane.

Before creating a workspace, always confirm the template choice with the user by:

	1. Listing the available templates that match their request.
	2. Recommending the most relevant option.
	2. Asking the user to confirm which template to use.

It is important to not create a workspace without confirming the template
choice with the user.

After creating a workspace, watch the build logs and wait for the workspace to
be ready before trying to use or connect to the workspace.
`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"user": map[string]any{
					"type":        "string",
					"description": userDescription("create a workspace"),
				},
				"template_id": map[string]any{
					"type":        "string",
					"description": "ID of the template to create the workspace from. The server resolves the active version. Prefer this over template_version_id unless you specifically need to pin a non-active version. Obtain this from coder_list_templates or coder_get_template.",
				},
				"template_version_id": map[string]any{
					"type":        "string",
					"description": "ID of a specific template version to create the workspace from. Use only when pinning a non-active version is required; otherwise prefer template_id. Mutually exclusive with template_id.",
				},
				"template_version_preset_id": map[string]any{
					"type":        "string",
					"description": "Optional ID of a template version preset to create the workspace from. Obtain available presets from coder_get_template. When set, the preset's parameter values take precedence over conflicting entries in rich_parameters.",
				},
				"name": map[string]any{
					"type":        "string",
					"description": "Name of the workspace to create.",
				},
				"rich_parameters": map[string]any{
					"type":                 "object",
					"description":          "Key/value pairs of rich parameters to pass to the template version to create the workspace.",
					"additionalProperties": map[string]any{"type": "string"},
				},
			},
			Required: []string{"name", "rich_parameters"},
		},
	},
	MCPAnnotations: mcpMutationAnnotations,
	Handler: func(ctx context.Context, deps Deps, args CreateWorkspaceArgs) (codersdk.Workspace, error) {

		if (args.TemplateID == "") == (args.TemplateVersionID == "") {
			return codersdk.Workspace{}, xerrors.New("exactly one of template_id or template_version_id must be provided")
		}
		var (
			tID  uuid.UUID
			tvID uuid.UUID
			err  error
		)
		if args.TemplateID != "" {
			tID, err = uuid.Parse(args.TemplateID)
			if err != nil {
				return codersdk.Workspace{}, xerrors.New("template_id must be a valid UUID")
			}
		}
		if args.TemplateVersionID != "" {
			tvID, err = uuid.Parse(args.TemplateVersionID)
			if err != nil {
				return codersdk.Workspace{}, xerrors.New("template_version_id must be a valid UUID")
			}
		}

		var tvPresetID uuid.UUID
		if args.TemplateVersionPresetID != "" {
			tvPresetID, err = uuid.Parse(args.TemplateVersionPresetID)
			if err != nil {
				return codersdk.Workspace{}, xerrors.New("template_version_preset_id must be a valid UUID")
			}
		}
		if args.User == "" {
			args.User = codersdk.Me
		}
		req := codersdk.CreateWorkspaceRequest{
			TemplateID:          tID,
			TemplateVersionID:   tvID,
			Name:                args.Name,
			RichParameterValues: richParametersFromMap(args.RichParameters),
		}
		if tvPresetID != uuid.Nil {
			req.TemplateVersionPresetID = tvPresetID
		}

		workspace, err := deps.coderClient.CreateUserWorkspace(ctx, args.User, req)
		if err != nil {
			return codersdk.Workspace{}, err
		}
		return workspace, nil
	},
}
View Source
var CreateWorkspaceBuild = Tool[CreateWorkspaceBuildArgs, codersdk.WorkspaceBuild]{
	Tool: aisdk.Tool{
		Name: ToolNameCreateWorkspaceBuild,
		Description: `Create a new workspace build for an existing workspace. Use this to start, stop, or delete.

For start transitions, optionally pass template_version_preset_id to apply a
preset (obtain available presets from coder_get_template), or rich_parameters
to override individual parameter values. Both fields are rejected on stop and
delete transitions because they are scoped to a starting build.

After creating a workspace build, watch the build logs and wait for the
workspace build to complete before trying to start another build or use or
connect to the workspace.
`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"workspace_id": map[string]any{
					"type": "string",
				},
				"transition": map[string]any{
					"type":        "string",
					"description": "The transition to perform. Must be one of: start, stop, delete",
					"enum":        []string{"start", "stop", "delete"},
				},
				"template_version_id": map[string]any{
					"type":        "string",
					"description": "(Optional) The template version ID to use for the workspace build. If not provided, the previously built version will be used.",
				},
				"template_version_preset_id": map[string]any{
					"type":        "string",
					"description": "(Optional) ID of a template version preset to apply. Only valid for start transitions. Obtain available presets from coder_get_template. Presets are scoped to the template version they were created on; pass template_version_id with the same version the preset came from when the workspace's current build is on a different version, otherwise the build may apply mismatched parameter defaults. When set, the preset's parameter values take precedence over conflicting entries in rich_parameters.",
				},
				"rich_parameters": map[string]any{
					"type":                 "object",
					"description":          "(Optional) Key/value pairs of rich parameters to apply to the build. Only valid for start transitions.",
					"additionalProperties": map[string]any{"type": "string"},
				},
			},
			Required: []string{"workspace_id", "transition"},
		},
	},
	MCPAnnotations: mcpDestructiveAnnotations,
	Handler: func(ctx context.Context, deps Deps, args CreateWorkspaceBuildArgs) (codersdk.WorkspaceBuild, error) {
		workspaceID, err := uuid.Parse(args.WorkspaceID)
		if err != nil {
			return codersdk.WorkspaceBuild{}, xerrors.Errorf("workspace_id must be a valid UUID: %w", err)
		}
		transition := codersdk.WorkspaceTransition(args.Transition)

		if transition != codersdk.WorkspaceTransitionStart {
			var errs []error
			if args.TemplateVersionPresetID != "" {
				errs = append(errs, xerrors.New("template_version_preset_id is only valid for start transitions"))
			}
			if len(args.RichParameters) > 0 {
				errs = append(errs, xerrors.New("rich_parameters is only valid for start transitions"))
			}
			if len(errs) > 0 {
				return codersdk.WorkspaceBuild{}, errors.Join(errs...)
			}
		}
		cbr := codersdk.CreateWorkspaceBuildRequest{
			Transition:          transition,
			RichParameterValues: richParametersFromMap(args.RichParameters),
		}
		if args.TemplateVersionID != "" {
			cbr.TemplateVersionID, err = uuid.Parse(args.TemplateVersionID)
			if err != nil {
				return codersdk.WorkspaceBuild{}, xerrors.Errorf("template_version_id must be a valid UUID: %w", err)
			}
		}
		if args.TemplateVersionPresetID != "" {
			cbr.TemplateVersionPresetID, err = uuid.Parse(args.TemplateVersionPresetID)
			if err != nil {
				return codersdk.WorkspaceBuild{}, xerrors.Errorf("template_version_preset_id must be a valid UUID: %w", err)
			}
		}
		return deps.coderClient.CreateWorkspaceBuild(ctx, workspaceID, cbr)
	},
}
View Source
var DeleteTemplate = Tool[DeleteTemplateArgs, codersdk.Response]{
	Tool: aisdk.Tool{
		Name:        ToolNameDeleteTemplate,
		Description: "Delete a template. This is irreversible.",
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"template_id": map[string]any{
					"type": "string",
				},
			},
			Required: []string{"template_id"},
		},
	},
	MCPAnnotations: mcpDestructiveAnnotations,
	Handler: func(ctx context.Context, deps Deps, args DeleteTemplateArgs) (codersdk.Response, error) {
		templateID, err := uuid.Parse(args.TemplateID)
		if err != nil {
			return codersdk.Response{}, xerrors.Errorf("template_id must be a valid UUID: %w", err)
		}
		err = deps.coderClient.DeleteTemplate(ctx, templateID)
		if err != nil {
			return codersdk.Response{}, err
		}
		return codersdk.Response{
			Message: "Template deleted successfully.",
		}, nil
	},
}
View Source
var DownloadChatFile = Tool[DownloadChatFileArgs, DownloadChatFileResponse]{
	Tool: aisdk.Tool{
		Name: ToolNameDownloadChatFile,
		Description: `Create a short-lived download URL for a file attached to a Coder Agents chat.

Address the file with file_id alone, or with chat_id and an exact file_name. The URL expires in about 5 minutes and needs no authentication header. Fetch it with curl -fSs -o <path> "<url>". Do not read binary contents into context.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"file_id": map[string]any{
					"type":        "string",
					"description": "Optional chat file UUID. Use this alone when the file ID is known.",
				},
				"chat_id": map[string]any{
					"type":        "string",
					"description": "Optional chat UUID. Use together with file_name when the file ID is unknown.",
				},
				"file_name": map[string]any{
					"type":        "string",
					"description": "Optional exact file name. Use together with chat_id.",
				},
			},
			Required: []string{},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args DownloadChatFileArgs) (DownloadChatFileResponse, error) {
		fileIDMode := args.FileID != "" && args.ChatID == "" && args.FileName == ""
		chatFileMode := args.FileID == "" && args.ChatID != "" && args.FileName != ""
		if !fileIDMode && !chatFileMode {
			return DownloadChatFileResponse{}, xerrors.New("provide exactly one addressing mode: file_id alone, or chat_id with file_name")
		}

		var fileID uuid.UUID
		if fileIDMode {
			var err error
			fileID, err = uuid.Parse(args.FileID)
			if err != nil {
				return DownloadChatFileResponse{}, xerrors.New("file_id must be a valid UUID")
			}
		} else {
			chatID, err := parseChatID(args.ChatID)
			if err != nil {
				return DownloadChatFileResponse{}, err
			}
			chat, err := codersdk.NewExperimentalClient(deps.coderClient).GetChat(ctx, chatID)
			if err != nil {
				return DownloadChatFileResponse{}, xerrors.Errorf("get chat: %w", err)
			}
			found := false
			for _, file := range chat.Files {
				if file.Name != args.FileName {
					continue
				}
				if found {
					return DownloadChatFileResponse{}, xerrors.Errorf("multiple chat files named %q; available files: %s", args.FileName, chatFilesDescription(chat.Files))
				}
				fileID = file.ID
				found = true
			}
			if !found {
				return DownloadChatFileResponse{}, xerrors.Errorf("no chat file named %q; available files: %s", args.FileName, chatFilesDescription(chat.Files))
			}
		}

		download, err := codersdk.NewExperimentalClient(deps.coderClient).ChatFileDownloadURL(ctx, fileID)
		if err != nil {
			return DownloadChatFileResponse{}, xerrors.Errorf("create chat file download URL: %w", err)
		}
		return DownloadChatFileResponse{
			FileID:    fileID.String(),
			Name:      download.Name,
			MimeType:  download.MimeType,
			SizeBytes: download.SizeBytes,
			SHA256:    download.SHA256,
			URL:       download.URL,
			ExpiresAt: download.ExpiresAt,
		}, nil
	},
}
View Source
var GetAuthenticatedUser = Tool[NoArgs, codersdk.User]{
	Tool: aisdk.Tool{
		Name:        ToolNameGetAuthenticatedUser,
		Description: "Get the currently authenticated user, similar to the `whoami` command.",
		Schema: aisdk.Schema{
			Properties: map[string]any{},
			Required:   []string{},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, _ NoArgs) (codersdk.User, error) {
		return deps.coderClient.User(ctx, "me")
	},
}
View Source
var GetChat = Tool[GetChatArgs, ChatToolStatus]{
	Tool: aisdk.Tool{
		Name:        ToolNameGetChat,
		Description: `Get the status of a Coder Agents chat, including its last error, last turn summary, workspace, and attached files.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"chat_id": map[string]any{
					"type":        "string",
					"description": chatIDDescription,
				},
			},
			Required: []string{"chat_id"},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args GetChatArgs) (ChatToolStatus, error) {
		chatID, err := parseChatID(args.ChatID)
		if err != nil {
			return ChatToolStatus{}, err
		}
		chat, err := codersdk.NewExperimentalClient(deps.coderClient).GetChat(ctx, chatID)
		if err != nil {
			return ChatToolStatus{}, xerrors.Errorf("get chat: %w", err)
		}
		return chatToolStatus(deps, chat), nil
	},
}
View Source
var GetChatMessages = Tool[GetChatMessagesArgs, GetChatMessagesResponse]{
	Tool: aisdk.Tool{
		Name: ToolNameGetChatMessages,
		Description: `Get messages from a Coder Agents chat in chronological order.

Only user-facing text content is returned (including lifecycle hook notices); tool calls and other internal parts are omitted. Prompts still queued behind a busy chat appear in queued_messages. Use before_id with next_before_id to page backward from the newest messages, or after_id with next_after_id to page forward.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"chat_id": map[string]any{
					"type":        "string",
					"description": chatIDDescription,
				},
				"limit": map[string]any{
					"type":        "integer",
					"description": "Maximum number of messages per page (1-200, default 50). Pages are newest-first unless after_id is set, which pages forward in chronological order.",
				},
				"before_id": map[string]any{
					"type":        "integer",
					"description": "Only fetch messages with an id lower than this cursor. Omit to fetch the newest messages.",
				},
				"after_id": map[string]any{
					"type":        "integer",
					"description": "Only fetch messages with an id greater than this cursor, in chronological order. Cannot be combined with before_id.",
				},
			},
			Required: []string{"chat_id"},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args GetChatMessagesArgs) (GetChatMessagesResponse, error) {
		chatID, err := parseChatID(args.ChatID)
		if err != nil {
			return GetChatMessagesResponse{}, err
		}
		if args.Limit < 0 || args.Limit > 200 {
			return GetChatMessagesResponse{}, xerrors.New("limit must be between 1 and 200")
		}
		if args.BeforeID < 0 {
			return GetChatMessagesResponse{}, xerrors.New("before_id must be a positive message id")
		}
		if args.AfterID < 0 {
			return GetChatMessagesResponse{}, xerrors.New("after_id must be a positive message id")
		}
		if args.BeforeID > 0 && args.AfterID > 0 {
			return GetChatMessagesResponse{}, xerrors.New("before_id and after_id cannot be used together")
		}
		var opts *codersdk.ChatMessagesPaginationOptions
		if args.Limit > 0 || args.BeforeID > 0 || args.AfterID > 0 {
			opts = &codersdk.ChatMessagesPaginationOptions{
				Limit:    args.Limit,
				BeforeID: args.BeforeID,
				AfterID:  args.AfterID,
			}
		}
		resp, err := codersdk.NewExperimentalClient(deps.coderClient).GetChatMessages(ctx, chatID, opts)
		if err != nil {
			return GetChatMessagesResponse{}, xerrors.Errorf("get chat messages: %w", err)
		}
		messages := make([]ChatToolMessage, 0, len(resp.Messages))
		if args.AfterID > 0 {
			for _, msg := range resp.Messages {
				if toolMessage, ok := chatToolMessage(msg); ok {
					messages = append(messages, toolMessage)
				}
			}
		} else {
			for i := len(resp.Messages) - 1; i >= 0; i-- {
				if toolMessage, ok := chatToolMessage(resp.Messages[i]); ok {
					messages = append(messages, toolMessage)
				}
			}
		}
		var queued []string
		for _, msg := range resp.QueuedMessages {
			text := userFacingText(msg.Content)
			if text == "" {
				// A queued prompt can carry only file parts; represent it
				// by its attachments instead of dropping it.
				var names []string
				for _, part := range msg.Content {
					if part.Type == codersdk.ChatMessagePartTypeFile && part.FileID.Valid {
						name := part.Name
						if name == "" {
							name = part.FileID.UUID.String()
						}
						names = append(names, name)
					}
				}
				if len(names) > 0 {
					text = "(attached files: " + strings.Join(names, ", ") + ")"
				}
			}
			if text != "" {
				queued = append(queued, text)
			}
		}
		var nextBeforeID, nextAfterID int64
		if len(resp.Messages) > 0 {
			if args.AfterID > 0 {

				nextAfterID = resp.Messages[0].ID
				for _, msg := range resp.Messages {
					if msg.ID > nextAfterID {
						nextAfterID = msg.ID
					}
				}
			} else if resp.HasMore {
				nextBeforeID = resp.Messages[0].ID
				for _, msg := range resp.Messages {
					if msg.ID < nextBeforeID {
						nextBeforeID = msg.ID
					}
				}
			}
		}
		return GetChatMessagesResponse{
			Messages:       messages,
			HasMore:        resp.HasMore,
			NextBeforeID:   nextBeforeID,
			NextAfterID:    nextAfterID,
			QueuedMessages: queued,
		}, nil
	},
}
View Source
var GetTemplate = Tool[GetTemplateArgs, TemplateDetail]{
	Tool: aisdk.Tool{
		Name: ToolNameGetTemplate,
		Description: `Get details about a workspace template, including its configurable parameters and available presets for the active version.

Use this after finding a template with coder_list_templates and before creating a workspace with coder_create_workspace. Presets, when present, can be passed to coder_create_workspace as template_version_preset_id.

When selecting a preset: if a preset is marked default and the user has not specified preferences, prefer that preset. Presets with desired_prebuild_instances > 0 may have prebuilt workspaces available for faster startup; prefer those when startup speed matters.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"template_id": map[string]any{
					"type":        "string",
					"description": "ID of the template to read details for. Obtain this from coder_list_templates.",
				},
			},
			Required: []string{"template_id"},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args GetTemplateArgs) (TemplateDetail, error) {
		templateID, err := uuid.Parse(args.TemplateID)
		if err != nil {
			return TemplateDetail{}, xerrors.Errorf("template_id must be a valid UUID: %w", err)
		}
		template, err := deps.coderClient.Template(ctx, templateID)
		if err != nil {
			return TemplateDetail{}, xerrors.Errorf("get template: %w", err)
		}

		if template.ActiveVersionID == uuid.Nil {
			return TemplateDetail{}, xerrors.New("template has no active version")
		}
		parameters, err := deps.coderClient.TemplateVersionRichParameters(ctx, template.ActiveVersionID)
		if err != nil {
			return TemplateDetail{}, xerrors.Errorf("get template parameters: %w", err)
		}
		presets, err := deps.coderClient.TemplateVersionPresets(ctx, template.ActiveVersionID)
		if err != nil {
			return TemplateDetail{}, xerrors.Errorf("get template presets: %w", err)
		}
		detail := TemplateDetail{
			MinimalTemplate: minimalTemplate(template),
			Parameters:      parameters,
		}
		for _, p := range presets {
			detail.Presets = append(detail.Presets, toPresetView(p))
		}
		return detail, nil
	},
}
View Source
var GetTemplateVersionLogs = Tool[GetTemplateVersionLogsArgs, []string]{
	Tool: aisdk.Tool{
		Name:        ToolNameGetTemplateVersionLogs,
		Description: "Get the logs of a template version. This is useful to check whether a template version successfully imports or not.",
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"template_version_id": map[string]any{
					"type": "string",
				},
			},
			Required: []string{"template_version_id"},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args GetTemplateVersionLogsArgs) ([]string, error) {
		templateVersionID, err := uuid.Parse(args.TemplateVersionID)
		if err != nil {
			return nil, xerrors.Errorf("template_version_id must be a valid UUID: %w", err)
		}

		logs, closer, err := deps.coderClient.TemplateVersionLogsAfter(ctx, templateVersionID, 0)
		if err != nil {
			return nil, err
		}
		defer closer.Close()
		var acc []string
		for log := range logs {
			acc = append(acc, log.Output)
		}
		return acc, nil
	},
}
View Source
var GetWorkspace = Tool[GetWorkspaceArgs, codersdk.Workspace]{
	Tool: aisdk.Tool{
		Name: ToolNameGetWorkspace,
		Description: `Get a workspace by name or ID.

This returns more data than list_workspaces to reduce token usage.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"workspace_id": map[string]any{
					"type":        "string",
					"description": workspaceDescription,
				},
			},
			Required: []string{"workspace_id"},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args GetWorkspaceArgs) (codersdk.Workspace, error) {
		return deps.coderClient.ResolveWorkspace(ctx, NormalizeWorkspaceInput(args.WorkspaceID))
	},
}
View Source
var GetWorkspaceAgentLogs = Tool[GetWorkspaceAgentLogsArgs, []string]{
	Tool: aisdk.Tool{
		Name: ToolNameGetWorkspaceAgentLogs,
		Description: `Get the logs of a workspace agent.

		More logs may appear after this call. It does not wait for the agent to finish.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"workspace_agent_id": map[string]any{
					"type": "string",
				},
			},
			Required: []string{"workspace_agent_id"},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args GetWorkspaceAgentLogsArgs) ([]string, error) {
		workspaceAgentID, err := uuid.Parse(args.WorkspaceAgentID)
		if err != nil {
			return nil, xerrors.Errorf("workspace_agent_id must be a valid UUID: %w", err)
		}
		logs, closer, err := deps.coderClient.WorkspaceAgentLogsAfter(ctx, workspaceAgentID, 0, false)
		if err != nil {
			return nil, err
		}
		defer closer.Close()
		var acc []string
		for logChunk := range logs {
			for _, log := range logChunk {
				acc = append(acc, log.Output)
			}
		}
		return acc, nil
	},
}
View Source
var GetWorkspaceBuildLogs = Tool[GetWorkspaceBuildLogsArgs, []string]{
	Tool: aisdk.Tool{
		Name: ToolNameGetWorkspaceBuildLogs,
		Description: `Get the logs of a workspace build.

		Useful for checking whether a workspace builds successfully or not.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"workspace_build_id": map[string]any{
					"type": "string",
				},
			},
			Required: []string{"workspace_build_id"},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args GetWorkspaceBuildLogsArgs) ([]string, error) {
		workspaceBuildID, err := uuid.Parse(args.WorkspaceBuildID)
		if err != nil {
			return nil, xerrors.Errorf("workspace_build_id must be a valid UUID: %w", err)
		}
		logs, closer, err := deps.coderClient.WorkspaceBuildLogsAfter(ctx, workspaceBuildID, 0)
		if err != nil {
			return nil, err
		}
		defer closer.Close()
		var acc []string
		for log := range logs {
			acc = append(acc, log.Output)
		}
		return acc, nil
	},
}
View Source
var InterruptChat = Tool[InterruptChatArgs, ChatToolStatus]{
	Tool: aisdk.Tool{
		Name:        ToolNameInterruptChat,
		Description: `Interrupt a running Coder Agents chat. Progress so far is preserved.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"chat_id": map[string]any{
					"type":        "string",
					"description": chatIDDescription,
				},
			},
			Required: []string{"chat_id"},
		},
	},
	MCPAnnotations: mcpMutationAnnotations,
	Handler: func(ctx context.Context, deps Deps, args InterruptChatArgs) (ChatToolStatus, error) {
		chatID, err := parseChatID(args.ChatID)
		if err != nil {
			return ChatToolStatus{}, err
		}
		chat, err := codersdk.NewExperimentalClient(deps.coderClient).InterruptChat(ctx, chatID)
		if err != nil {
			return ChatToolStatus{}, xerrors.Errorf("interrupt chat: %w", err)
		}
		return chatToolStatus(deps, chat), nil
	},
}
View Source
var ListChatModelConfigs = Tool[ListChatModelConfigsArgs, ListChatModelConfigsResponse]{
	Tool: aisdk.Tool{
		Name: ToolNameListChatModelConfigs,
		Description: `List the enabled chat models available for Coder Agents chats. Use a model config ID with coder_create_chat to pick a model.

Model configs are organization-scoped. The response includes the organization_id the models belong to; pass it as coder_create_chat's organization_id together with the chosen model config ID.

Per-user provider credentials are validated when creating a chat, so coder_create_chat can still reject a listed model with an explanatory error.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"organization_id": map[string]any{
					"type":        "string",
					"description": "Organization UUID.",
				},
			},
			Required: []string{},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args ListChatModelConfigsArgs) (ListChatModelConfigsResponse, error) {
		organizationID, err := resolveOrganization(ctx, deps, args.OrganizationID)
		if err != nil {
			return ListChatModelConfigsResponse{}, err
		}

		response, err := codersdk.NewExperimentalClient(deps.coderClient).ChatModels(ctx, organizationID)
		if err != nil {
			return ListChatModelConfigsResponse{}, xerrors.Errorf("list chat model configs: %w", err)
		}
		providerEnabled := make(map[uuid.UUID]bool, len(response.Providers))
		for _, provider := range response.Providers {
			providerEnabled[provider.ID] = provider.Enabled
		}
		summaries := make([]ChatModelConfigSummary, 0, len(response.Models))
		for _, config := range response.Models {
			if !config.Enabled || !providerEnabled[config.AIProviderID] {
				continue
			}
			summaries = append(summaries, ChatModelConfigSummary{
				ID:          config.ID.String(),
				Model:       config.Model,
				DisplayName: config.DisplayName,
				IsDefault:   config.IsDefault,
			})
		}
		return ListChatModelConfigsResponse{
			OrganizationID: organizationID.String(),
			ModelConfigs:   summaries,
		}, nil
	},
}
View Source
var ListChats = Tool[ListChatsArgs, ListChatsResponse]{
	Tool: aisdk.Tool{
		Name:        ToolNameListChats,
		Description: `List Coder Agents chats, optionally filtered by labels or a search query.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"labels": map[string]any{
					"type":                 "object",
					"description":          "Optional exact-match string key/value labels.",
					"additionalProperties": map[string]any{"type": "string"},
				},
				"query": map[string]any{
					"type":        "string",
					"description": "Optional chat search query using fielded terms; bare text is rejected. Supported fields: search:<text> (full-text, cannot combine with title, pr_title, or pr), title:<text>, repo:<owner/name>, pr:<number>, pr_title:<text>, pr_status:<draft|open|merged|closed|none>, diff_url:<url>, archived:<true|false>, has_unread:<true|false>, status:<waiting|running|error|requires_action|interrupting>, source:<created_by_me|shared_with_me>. Quote values containing spaces or colons (URLs always need quoting), e.g. search:\"failed deployment\" or diff_url:\"https://github.com/org/repo/pull/1\".",
				},
				"limit": map[string]any{
					"type":        "integer",
					"description": "Maximum chats to return (1-100, default 25).",
				},
			},
			Required: []string{},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args ListChatsArgs) (ListChatsResponse, error) {
		if args.Limit < 0 || args.Limit > 100 {
			return ListChatsResponse{}, xerrors.New("limit must be between 1 and 100")
		}
		limit := args.Limit
		if limit == 0 {
			limit = 25
		}
		chats, err := codersdk.NewExperimentalClient(deps.coderClient).ListChats(ctx, &codersdk.ListChatsOptions{
			Query:  args.Query,
			Labels: args.Labels,
			Pagination: codersdk.Pagination{
				Limit: limit,
			},
		})
		if err != nil {
			return ListChatsResponse{}, xerrors.Errorf("list chats: %w", err)
		}
		resp := ListChatsResponse{Chats: make([]ChatToolStatus, len(chats))}
		for i, chat := range chats {
			resp.Chats[i] = chatToolStatus(deps, chat)
		}
		return resp, nil
	},
}
View Source
var ListOrganizations = Tool[NoArgs, []codersdk.Organization]{
	Tool: aisdk.Tool{
		Name:        ToolNameListOrganizations,
		Description: "List organizations the authenticated user belongs to, including IDs, names, and display names. Membership does not grant permission to perform every organization-scoped action.",
		Schema: aisdk.Schema{
			Properties: map[string]any{},
			Required:   []string{},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, _ NoArgs) ([]codersdk.Organization, error) {
		organizations, err := deps.coderClient.OrganizationsByUser(ctx, codersdk.Me)
		if err != nil {
			return nil, xerrors.Errorf("list organizations: %w", err)
		}
		if organizations == nil {
			organizations = []codersdk.Organization{}
		}
		return organizations, nil
	},
}

ListOrganizations lists the authenticated user's visible memberships.

View Source
var ListTemplateVersionParameters = Tool[ListTemplateVersionParametersArgs, []codersdk.TemplateVersionParameter]{
	Tool: aisdk.Tool{
		Name:        ToolNameListTemplateVersionParams,
		Description: "Get the parameters for a template version. You can refer to these as workspace parameters to the user, as they are typically important for creating a workspace.",
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"template_version_id": map[string]any{
					"type": "string",
				},
			},
			Required: []string{"template_version_id"},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args ListTemplateVersionParametersArgs) ([]codersdk.TemplateVersionParameter, error) {
		templateVersionID, err := uuid.Parse(args.TemplateVersionID)
		if err != nil {
			return nil, xerrors.Errorf("template_version_id must be a valid UUID: %w", err)
		}
		parameters, err := deps.coderClient.TemplateVersionRichParameters(ctx, templateVersionID)
		if err != nil {
			return nil, err
		}
		return parameters, nil
	},
}
View Source
var ListTemplates = Tool[NoArgs, []MinimalTemplate]{
	Tool: aisdk.Tool{
		Name:        ToolNameListTemplates,
		Description: "Lists templates for the authenticated user. agents_allowed indicates whether Coder Agents (chats) may create workspaces from the template.",
		Schema: aisdk.Schema{
			Properties: map[string]any{},
			Required:   []string{},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, _ NoArgs) ([]MinimalTemplate, error) {
		templates, err := deps.coderClient.Templates(ctx, codersdk.TemplateFilter{})
		if err != nil {
			return nil, err
		}
		minimalTemplates := make([]MinimalTemplate, len(templates))
		for i, template := range templates {
			minimalTemplates[i] = minimalTemplate(template)
		}
		return minimalTemplates, nil
	},
}
View Source
var ListWorkspaces = Tool[ListWorkspacesArgs, []MinimalWorkspace]{
	Tool: aisdk.Tool{
		Name:        ToolNameListWorkspaces,
		Description: "Lists workspaces for the authenticated user.",
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"owner": map[string]any{
					"type":        "string",
					"description": "The owner of the workspaces to list. Use \"me\" to list workspaces for the authenticated user. If you do not specify an owner, \"me\" will be assumed by default.",
				},
			},
			Required: []string{},
		},
	},
	MCPAnnotations: mcpReadOnlyAnnotations,
	Handler: func(ctx context.Context, deps Deps, args ListWorkspacesArgs) ([]MinimalWorkspace, error) {
		owner := args.Owner
		if owner == "" {
			owner = codersdk.Me
		}
		workspaces, err := deps.coderClient.Workspaces(ctx, codersdk.WorkspaceFilter{
			Owner: owner,
		})
		if err != nil {
			return nil, err
		}
		minimalWorkspaces := make([]MinimalWorkspace, len(workspaces.Workspaces))
		for i, workspace := range workspaces.Workspaces {
			minimalWorkspaces[i] = MinimalWorkspace{
				OrganizationID:          workspace.OrganizationID.String(),
				ID:                      workspace.ID.String(),
				Name:                    workspace.Name,
				TemplateID:              workspace.TemplateID.String(),
				TemplateName:            workspace.TemplateName,
				TemplateDisplayName:     workspace.TemplateDisplayName,
				TemplateIcon:            workspace.TemplateIcon,
				TemplateActiveVersionID: workspace.TemplateActiveVersionID,
				Outdated:                workspace.Outdated,
			}
		}
		return minimalWorkspaces, nil
	},
}
View Source
var ReportTask = Tool[ReportTaskArgs, codersdk.Response]{
	Tool: aisdk.Tool{
		Name: ToolNameReportTask,
		Description: `Report progress on your work.

The user observes your work through a Task UI. To keep them updated
on your progress, or if you need help - use this tool.

Good Tasks
- "Cloning the repository <repository-url>"
- "Working on <feature-name>"
- "Figuring our why <issue> is happening"

Bad Tasks
- "I'm working on it"
- "I'm trying to fix it"
- "I'm trying to implement <feature-name>"

Use the "state" field to indicate your progress. Periodically report
progress with state "working" to keep the user updated. It is not possible to send too many updates!

ONLY report a "complete", "idle", or "failure" state if you have FULLY completed the task.
`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"summary": map[string]any{
					"type":        "string",
					"description": "A concise summary of your current progress on the task. This must be less than 160 characters in length and must not include newlines or other control characters.",
				},
				"link": map[string]any{
					"type":        "string",
					"description": "A link to a relevant resource, such as a PR or issue.",
				},
				"state": map[string]any{
					"type":        "string",
					"description": "The state of your task. This can be one of the following: working, complete, idle, or failure. Select the state that best represents your current progress.",
					"enum": []string{
						string(codersdk.WorkspaceAppStatusStateWorking),
						string(codersdk.WorkspaceAppStatusStateComplete),
						string(codersdk.WorkspaceAppStatusStateIdle),
						string(codersdk.WorkspaceAppStatusStateFailure),
					},
				},
			},
			Required: []string{"summary", "link", "state"},
		},
	},
	MCPAnnotations:     mcpMutationAnnotations,
	UserClientOptional: true,
	Handler: func(_ context.Context, deps Deps, args ReportTaskArgs) (codersdk.Response, error) {
		if len(args.Summary) > 160 {
			return codersdk.Response{}, xerrors.New("summary must be less than 160 characters")
		}

		if deps.report == nil {
			return codersdk.Response{}, xerrors.New("task reporting not available. Please ensure a task reporter is configured.")
		}
		err := deps.report(args)
		if err != nil {
			return codersdk.Response{}, err
		}
		return codersdk.Response{
			Message: "Thanks for reporting!",
		}, nil
	},
}
View Source
var SendChatMessage = Tool[SendChatMessageArgs, SendChatMessageResponse]{
	Tool: aisdk.Tool{
		Name:        ToolNameSendChatMessage,
		Description: `Send a message to a Coder Agents chat.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"chat_id": map[string]any{
					"type":        "string",
					"description": chatIDDescription,
				},
				"text": map[string]any{
					"type":        "string",
					"description": "The message to send.",
				},
				"busy_behavior": map[string]any{
					"type":        "string",
					"description": "What to do when the chat is already processing: \"queue\" (default) processes the message after the current run, \"interrupt\" stops the current run first.",
					"enum": []string{
						string(codersdk.ChatBusyBehaviorQueue),
						string(codersdk.ChatBusyBehaviorInterrupt),
					},
				},
			},
			Required: []string{"chat_id", "text"},
		},
	},
	MCPAnnotations: mcpMutationAnnotations,
	Handler: func(ctx context.Context, deps Deps, args SendChatMessageArgs) (SendChatMessageResponse, error) {
		chatID, err := parseChatID(args.ChatID)
		if err != nil {
			return SendChatMessageResponse{}, err
		}
		if args.Text == "" {
			return SendChatMessageResponse{}, xerrors.New("text is required")
		}
		busyBehavior := args.BusyBehavior
		switch busyBehavior {
		case "":
			busyBehavior = codersdk.ChatBusyBehaviorQueue
		case codersdk.ChatBusyBehaviorQueue, codersdk.ChatBusyBehaviorInterrupt:
		default:
			return SendChatMessageResponse{}, xerrors.New(`busy_behavior must be "queue" or "interrupt"`)
		}
		resp, err := codersdk.NewExperimentalClient(deps.coderClient).CreateChatMessage(ctx, chatID, codersdk.CreateChatMessageRequest{
			Content: []codersdk.ChatInputPart{{
				Type: codersdk.ChatInputPartTypeText,
				Text: args.Text,
			}},
			BusyBehavior: busyBehavior,
		})
		if err != nil {
			return SendChatMessageResponse{}, xerrors.Errorf("send chat message: %w", err)
		}
		return SendChatMessageResponse{
			Queued:   resp.Queued,
			Warnings: resp.Warnings,
		}, nil
	},
}
View Source
var UpdateTemplateActiveVersion = Tool[UpdateTemplateActiveVersionArgs, string]{
	Tool: aisdk.Tool{
		Name:        ToolNameUpdateTemplateActiveVersion,
		Description: "Update the active version of a template. This is helpful when iterating on templates.",
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"template_id": map[string]any{
					"type": "string",
				},
				"template_version_id": map[string]any{
					"type": "string",
				},
			},
			Required: []string{"template_id", "template_version_id"},
		},
	},
	MCPAnnotations: mcpMutationAnnotations,
	Handler: func(ctx context.Context, deps Deps, args UpdateTemplateActiveVersionArgs) (string, error) {
		templateID, err := uuid.Parse(args.TemplateID)
		if err != nil {
			return "", xerrors.Errorf("template_id must be a valid UUID: %w", err)
		}
		templateVersionID, err := uuid.Parse(args.TemplateVersionID)
		if err != nil {
			return "", xerrors.Errorf("template_version_id must be a valid UUID: %w", err)
		}
		err = deps.coderClient.UpdateActiveTemplateVersion(ctx, templateID, codersdk.UpdateActiveTemplateVersion{
			ID: templateVersionID,
		})
		if err != nil {
			return "", err
		}
		return "Successfully updated active version!", nil
	},
}
View Source
var UploadTarFile = Tool[UploadTarFileArgs, codersdk.UploadResponse]{
	Tool: aisdk.Tool{
		Name:        ToolNameUploadTarFile,
		Description: `Create and upload a tar file by key/value mapping of file names to file contents. Use this to create template versions. Reference the tool description of "create_template_version" to understand template requirements.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"files": map[string]any{
					"type":                 "object",
					"description":          "A map of file names to file contents.",
					"additionalProperties": map[string]any{"type": "string"},
				},
			},
			Required: []string{"files"},
		},
	},
	MCPAnnotations: mcpMutationAnnotations,
	Handler: func(ctx context.Context, deps Deps, args UploadTarFileArgs) (codersdk.UploadResponse, error) {
		pipeReader, pipeWriter := io.Pipe()
		done := make(chan struct{})
		go func() {
			defer func() {
				_ = pipeWriter.Close()
				close(done)
			}()
			tarWriter := tar.NewWriter(pipeWriter)
			for name, content := range args.Files {
				header := &tar.Header{
					Name: name,
					Size: int64(len(content)),
					Mode: 0o644,
				}
				if err := tarWriter.WriteHeader(header); err != nil {
					_ = pipeWriter.CloseWithError(err)
					return
				}
				if _, err := tarWriter.Write([]byte(content)); err != nil {
					_ = pipeWriter.CloseWithError(err)
					return
				}
			}
			if err := tarWriter.Close(); err != nil {
				_ = pipeWriter.CloseWithError(err)
			}
		}()

		resp, err := deps.coderClient.Upload(ctx, codersdk.ContentTypeTar, pipeReader)
		if err != nil {
			_ = pipeReader.CloseWithError(err)
			<-done
			return codersdk.UploadResponse{}, err
		}
		<-done
		return resp, nil
	},
}
View Source
var WorkspaceBash = Tool[WorkspaceBashArgs, WorkspaceBashResult]{
	Tool: aisdk.Tool{
		Name: ToolNameWorkspaceBash,
		Description: `Execute a bash command in a Coder workspace.

This tool provides the same functionality as the 'coder ssh <workspace> <command>' CLI command.
It automatically starts the workspace if it's stopped and waits for the agent to be ready.
The output is trimmed of leading and trailing whitespace.

The workspace parameter supports various formats:
- workspace (uses current user)
- owner/workspace
- owner--workspace
- workspace.agent (specific agent)
- owner/workspace.agent

The timeout_ms parameter specifies the command timeout in milliseconds (defaults to 60000ms, maximum of 300000ms).
If the command times out, all output captured up to that point is returned with a cancellation message.

For background commands (background: true), output is captured until the timeout is reached, then the command
continues running in the background. The captured output is returned as the result.

For file operations (list, write, edit), always prefer the dedicated file tools.
Do not use bash commands (ls, cat, echo, heredoc, etc.) to list, write, or read
files when the file tools are available. The bash tool should be used for:

	- Running commands and scripts
	- Installing packages
	- Starting services
	- Executing programs

Examples:
- workspace: "john/dev-env", command: "git status", timeout_ms: 30000
- workspace: "my-workspace", command: "npm run dev", background: true, timeout_ms: 10000
- workspace: "my-workspace.main", command: "docker ps"`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"workspace": map[string]any{
					"type":        "string",
					"description": "The workspace name in format [owner/]workspace[.agent]. If owner is not specified, the authenticated user is used.",
				},
				"command": map[string]any{
					"type":        "string",
					"description": "The bash command to execute in the workspace.",
				},
				"timeout_ms": map[string]any{
					"type":        "integer",
					"description": "Command timeout in milliseconds. Defaults to 60000ms (60 seconds) if not specified.",
					"default":     60000,
					"minimum":     1,
				},
				"background": map[string]any{
					"type":        "boolean",
					"description": "Whether to run the command in the background. Output is captured until timeout, then the command continues running in the background.",
				},
			},
			Required: []string{"workspace", "command"},
		},
	},
	MCPAnnotations: mcpDestructiveAnnotations,
	Handler: func(ctx context.Context, deps Deps, args WorkspaceBashArgs) (res WorkspaceBashResult, err error) {
		if args.Workspace == "" {
			return WorkspaceBashResult{}, xerrors.New("workspace name cannot be empty")
		}
		if args.Command == "" {
			return WorkspaceBashResult{}, xerrors.New("command cannot be empty")
		}

		ctx, cancel := context.WithTimeoutCause(ctx, 5*time.Minute, xerrors.New("MCP handler timeout after 5 min"))
		defer cancel()

		conn, err := openAgentConn(ctx, deps, args.Workspace)
		if err != nil {
			return WorkspaceBashResult{}, err
		}
		defer conn.Close()

		sshClient, err := conn.SSHClient(ctx)
		if err != nil {
			return WorkspaceBashResult{}, xerrors.Errorf("failed to create SSH client: %w", err)
		}
		defer sshClient.Close()

		session, err := sshClient.NewSession()
		if err != nil {
			return WorkspaceBashResult{}, xerrors.Errorf("failed to create SSH session: %w", err)
		}
		defer session.Close()

		timeoutMs := args.TimeoutMs
		defaultTimeoutMs := 60000
		if timeoutMs <= 0 {
			timeoutMs = defaultTimeoutMs
		}
		command := args.Command
		if args.Background {

			command = fmt.Sprintf("nohup %s </dev/null 2>&1", args.Command)
		}

		commandCtx, commandCancel := context.WithTimeout(ctx, time.Duration(timeoutMs)*time.Millisecond)
		defer commandCancel()

		output, err := executeCommandWithTimeout(commandCtx, session, command)
		outputStr := strings.TrimSpace(string(output))

		if err != nil {

			if errors.Is(context.Cause(commandCtx), context.DeadlineExceeded) {
				if args.Background {
					outputStr += "\nCommand continues running in background"
				} else {
					outputStr += "\nCommand canceled due to timeout"
				}
				return WorkspaceBashResult{
					Output:   outputStr,
					ExitCode: 124,
				}, nil
			}

			exitCode := 1
			var exitErr *gossh.ExitError
			if errors.As(err, &exitErr) {
				exitCode = exitErr.ExitStatus()
			}

			return WorkspaceBashResult{
				Output:   outputStr,
				ExitCode: exitCode,
			}, nil
		}

		return WorkspaceBashResult{
			Output:   outputStr,
			ExitCode: 0,
		}, nil
	},
}
View Source
var WorkspaceEditFile = Tool[WorkspaceEditFileArgs, WorkspaceEditFilesResponse]{
	Tool: aisdk.Tool{
		Name:        ToolNameWorkspaceEditFile,
		Description: `Edit a file in a workspace.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"workspace": map[string]any{
					"type":        "string",
					"description": workspaceAgentDescription,
				},
				"path": map[string]any{
					"type":        "string",
					"description": "The absolute path of the file to write in the workspace.",
				},
				"edits": map[string]any{
					"type":        "array",
					"description": "An array of edit operations.",
					"items": map[string]any{
						"type": "object",
						"properties": map[string]any{
							"old_text": map[string]any{
								"type":        "string",
								"description": "The existing text to replace. Matching is fuzzy: whitespace and indentation differences are tolerated. Must uniquely match exactly one location in the file unless replace_all is true. Include enough surrounding context to make the match unique.",
							},
							"new_text": map[string]any{
								"type":        "string",
								"description": "The new text that replaces the old text.",
							},
							"replace_all": map[string]any{
								"type":        "boolean",
								"description": "When true, replaces all occurrences of old_text. Defaults to false, which requires old_text to match exactly once.",
							},
						},
						"required": []string{"old_text", "new_text"},
					},
				},
			},
			Required: []string{"path", "workspace", "edits"},
		},
	},
	MCPAnnotations:     mcpDestructiveAnnotations,
	UserClientOptional: true,
	Handler: func(ctx context.Context, deps Deps, args WorkspaceEditFileArgs) (WorkspaceEditFilesResponse, error) {
		conn, err := openAgentConn(ctx, deps, args.Workspace)
		if err != nil {
			return WorkspaceEditFilesResponse{}, err
		}
		defer conn.Close()

		resp, err := conn.EditFiles(ctx, workspacesdk.FileEditRequest{
			Files: []workspacesdk.FileEdits{
				{
					Path:  args.Path,
					Edits: args.Edits,
				},
			},
			IncludeDiff: true,
		})
		if err != nil {
			return WorkspaceEditFilesResponse{}, err
		}

		return WorkspaceEditFilesResponse{
			Message: "File edited successfully.",
			Files:   resp.Files,
		}, nil
	},
}
View Source
var WorkspaceEditFiles = Tool[WorkspaceEditFilesArgs, WorkspaceEditFilesResponse]{
	Tool: aisdk.Tool{
		Name:        ToolNameWorkspaceEditFiles,
		Description: `Edit one or more files in a workspace.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"workspace": map[string]any{
					"type":        "string",
					"description": workspaceAgentDescription,
				},
				"files": map[string]any{
					"type":        "array",
					"description": "An array of files to edit.",
					"items": map[string]any{
						"type": "object",
						"properties": map[string]any{
							"path": map[string]any{
								"type":        "string",
								"description": "The absolute path of the file to write in the workspace.",
							},
							"edits": map[string]any{
								"type":        "array",
								"description": "An array of edit operations.",
								"items": map[string]any{
									"type": "object",
									"properties": map[string]any{
										"old_text": map[string]any{
											"type":        "string",
											"description": "The existing text to replace. Matching is fuzzy: whitespace and indentation differences are tolerated. Must uniquely match exactly one location in the file unless replace_all is true. Include enough surrounding context to make the match unique.",
										},
										"new_text": map[string]any{
											"type":        "string",
											"description": "The new text that replaces the old text.",
										},
										"replace_all": map[string]any{
											"type":        "boolean",
											"description": "When true, replaces all occurrences of old_text. Defaults to false, which requires old_text to match exactly once.",
										},
									},
									"required": []string{"old_text", "new_text"},
								},
							},
						},
						"required": []string{"path", "edits"},
					},
				},
			},
			Required: []string{"workspace", "files"},
		},
	},
	MCPAnnotations:     mcpDestructiveAnnotations,
	UserClientOptional: true,
	Handler: func(ctx context.Context, deps Deps, args WorkspaceEditFilesArgs) (WorkspaceEditFilesResponse, error) {
		conn, err := openAgentConn(ctx, deps, args.Workspace)
		if err != nil {
			return WorkspaceEditFilesResponse{}, err
		}
		defer conn.Close()

		resp, err := conn.EditFiles(ctx, workspacesdk.FileEditRequest{
			Files:       args.Files,
			IncludeDiff: true,
		})
		if err != nil {
			return WorkspaceEditFilesResponse{}, err
		}

		return WorkspaceEditFilesResponse{
			Message: "File(s) edited successfully.",
			Files:   resp.Files,
		}, nil
	},
}
View Source
var WorkspaceLS = Tool[WorkspaceLSArgs, WorkspaceLSResponse]{
	Tool: aisdk.Tool{
		Name:        ToolNameWorkspaceLS,
		Description: `List directories in a workspace.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"workspace": map[string]any{
					"type":        "string",
					"description": workspaceAgentDescription,
				},
				"path": map[string]any{
					"type":        "string",
					"description": "The absolute path of the directory in the workspace to list.",
				},
			},
			Required: []string{"path", "workspace"},
		},
	},
	MCPAnnotations:     mcpReadOnlyAnnotations,
	UserClientOptional: true,
	Handler: func(ctx context.Context, deps Deps, args WorkspaceLSArgs) (WorkspaceLSResponse, error) {
		conn, err := openAgentConn(ctx, deps, args.Workspace)
		if err != nil {
			return WorkspaceLSResponse{}, err
		}
		defer conn.Close()

		res, err := conn.LS(ctx, args.Path, workspacesdk.LSRequest{})
		if err != nil {
			return WorkspaceLSResponse{}, err
		}

		contents := make([]WorkspaceLSFile, len(res.Contents))
		for i, f := range res.Contents {
			contents[i] = WorkspaceLSFile{
				Path:  f.AbsolutePathString,
				IsDir: f.IsDir,
			}
		}
		return WorkspaceLSResponse{Contents: contents}, nil
	},
}
View Source
var WorkspaceListApps = Tool[WorkspaceListAppsArgs, WorkspaceListAppsResponse]{
	Tool: aisdk.Tool{
		Name:        ToolNameWorkspaceListApps,
		Description: `List the URLs of Coder apps running in a workspace for a single agent.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"workspace": map[string]any{
					"type":        "string",
					"description": workspaceAgentDescription,
				},
			},
			Required: []string{"workspace"},
		},
	},
	MCPAnnotations:     mcpReadOnlyAnnotations,
	UserClientOptional: true,
	Handler: func(ctx context.Context, deps Deps, args WorkspaceListAppsArgs) (WorkspaceListAppsResponse, error) {
		workspaceName := NormalizeWorkspaceInput(args.Workspace)
		_, workspaceAgent, err := findWorkspaceAndAgent(ctx, deps.coderClient, workspaceName)
		if err != nil {
			return WorkspaceListAppsResponse{}, xerrors.Errorf("failed to find workspace: %w", err)
		}

		var res WorkspaceListAppsResponse
		for _, app := range workspaceAgent.Apps {
			name := app.DisplayName
			if name == "" {
				name = app.Slug
			}
			res.Apps = append(res.Apps, WorkspaceListApp{
				Name: name,
				URL:  app.URL,
			})
		}

		return res, nil
	},
}
View Source
var WorkspacePortForward = Tool[WorkspacePortForwardArgs, WorkspacePortForwardResponse]{
	Tool: aisdk.Tool{
		Name:        ToolNameWorkspacePortForward,
		Description: `Fetch URLs that forward to the specified port.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"workspace": map[string]any{
					"type":        "string",
					"description": workspaceAgentDescription,
				},
				"port": map[string]any{
					"type":        "integer",
					"description": "The port to forward.",
				},
			},
			Required: []string{"workspace", "port"},
		},
	},
	MCPAnnotations:     mcpReadOnlyAnnotations,
	UserClientOptional: true,
	Handler: func(ctx context.Context, deps Deps, args WorkspacePortForwardArgs) (WorkspacePortForwardResponse, error) {
		workspaceName := NormalizeWorkspaceInput(args.Workspace)
		workspace, workspaceAgent, err := findWorkspaceAndAgent(ctx, deps.coderClient, workspaceName)
		if err != nil {
			return WorkspacePortForwardResponse{}, xerrors.Errorf("failed to find workspace: %w", err)
		}
		res, err := deps.coderClient.AppHost(ctx)
		if err != nil {
			return WorkspacePortForwardResponse{}, xerrors.Errorf("failed to get app host: %w", err)
		}
		if res.Host == "" {
			return WorkspacePortForwardResponse{}, xerrors.New("no app host for forwarding has been configured")
		}
		url := appurl.ApplicationURL{
			AppSlugOrPort: strconv.Itoa(args.Port),
			AgentName:     workspaceAgent.Name,
			WorkspaceName: workspace.Name,
			Username:      workspace.OwnerName,
		}
		return WorkspacePortForwardResponse{
			URL: deps.coderClient.URL.Scheme + "://" + strings.Replace(res.Host, "*", url.String(), 1),
		}, nil
	},
}
View Source
var WorkspaceReadFile = Tool[WorkspaceReadFileArgs, WorkspaceReadFileResponse]{
	Tool: aisdk.Tool{
		Name:        ToolNameWorkspaceReadFile,
		Description: `Read from a file in a workspace.`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"workspace": map[string]any{
					"type":        "string",
					"description": workspaceAgentDescription,
				},
				"path": map[string]any{
					"type":        "string",
					"description": "The absolute path of the file to read in the workspace.",
				},
				"offset": map[string]any{
					"type":        "integer",
					"description": "A byte offset indicating where in the file to start reading. Defaults to zero. An empty string indicates the end of the file has been reached.",
				},
				"limit": map[string]any{
					"type":        "integer",
					"description": "The number of bytes to read. Cannot exceed 1 MiB. Defaults to the full size of the file or 1 MiB, whichever is lower.",
				},
			},
			Required: []string{"path", "workspace"},
		},
	},
	MCPAnnotations:     mcpReadOnlyAnnotations,
	UserClientOptional: true,
	Handler: func(ctx context.Context, deps Deps, args WorkspaceReadFileArgs) (WorkspaceReadFileResponse, error) {
		conn, err := openAgentConn(ctx, deps, args.Workspace)
		if err != nil {
			return WorkspaceReadFileResponse{}, err
		}
		defer conn.Close()

		limit := args.Limit
		if limit == 0 {
			limit = maxFileLimit
		} else if limit > maxFileLimit {
			return WorkspaceReadFileResponse{}, xerrors.Errorf("limit must be %d or less, got %d", maxFileLimit, limit)
		}

		reader, mimeType, err := conn.ReadFile(ctx, args.Path, args.Offset, limit)
		if err != nil {
			return WorkspaceReadFileResponse{}, err
		}
		defer reader.Close()

		bs, err := io.ReadAll(reader)
		if err != nil {
			return WorkspaceReadFileResponse{}, xerrors.Errorf("read response body: %w", err)
		}

		return WorkspaceReadFileResponse{Content: bs, MimeType: mimeType}, nil
	},
}
View Source
var WorkspaceWriteFile = Tool[WorkspaceWriteFileArgs, codersdk.Response]{
	Tool: aisdk.Tool{
		Name: ToolNameWorkspaceWriteFile,
		Description: `Write a file in a workspace.

If a file write fails due to syntax errors or encoding issues, do NOT switch
to using bash commands as a workaround. Instead:

	1. Read the error message carefully to identify the issue
	2. Fix the content encoding/syntax
	3. Retry with this tool

The content parameter expects base64-encoded bytes. Ensure your source content
is correct before encoding it. If you encounter errors, decode and verify the
content you are trying to write, then re-encode it properly.
`,
		Schema: aisdk.Schema{
			Properties: map[string]any{
				"workspace": map[string]any{
					"type":        "string",
					"description": workspaceAgentDescription,
				},
				"path": map[string]any{
					"type":        "string",
					"description": "The absolute path of the file to write in the workspace.",
				},
				"content": map[string]any{
					"type":        "string",
					"description": "The base64-encoded bytes to write to the file.",
				},
			},
			Required: []string{"path", "workspace", "content"},
		},
	},
	MCPAnnotations:     mcpDestructiveAnnotations,
	UserClientOptional: true,
	Handler: func(ctx context.Context, deps Deps, args WorkspaceWriteFileArgs) (codersdk.Response, error) {
		conn, err := openAgentConn(ctx, deps, args.Workspace)
		if err != nil {
			return codersdk.Response{}, err
		}
		defer conn.Close()

		reader := bytes.NewReader(args.Content)
		err = conn.WriteFile(ctx, args.Path, reader)
		if err != nil {
			return codersdk.Response{}, err
		}

		return codersdk.Response{
			Message: "File written successfully.",
		}, nil
	},
}

Functions

func NormalizeWorkspaceInput added in v2.25.0

func NormalizeWorkspaceInput(input string) string

NormalizeWorkspaceInput converts workspace name input to standard format. Handles the following input formats:

  • workspace → workspace
  • workspace.agent → workspace.agent
  • owner/workspace → owner/workspace
  • owner--workspace → owner/workspace
  • owner/workspace.agent → owner/workspace.agent
  • owner--workspace.agent → owner/workspace.agent
  • agent.workspace.owner → owner/workspace.agent (Coder Connect format)

func WithAgentConnFunc added in v2.33.0

func WithAgentConnFunc(agentConnFn workspacesdk.AgentConnFunc) func(*Deps)

WithAgentConnFunc overrides how workspace tools open logical connections to workspace agents.

func WithTaskReporter added in v2.24.0

func WithTaskReporter(fn func(ReportTaskArgs) error) func(*Deps)

Types

type ArchiveChatArgs added in v2.37.0

type ArchiveChatArgs struct {
	ChatID string `json:"chat_id"`
}

type ArgumentValidationError

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

ArgumentValidationError reports that tool arguments do not satisfy the declared schema or cannot be decoded into the tool's argument type.

func (*ArgumentValidationError) Error

func (e *ArgumentValidationError) Error() string

func (*ArgumentValidationError) Unwrap

func (e *ArgumentValidationError) Unwrap() error

Unwrap returns the underlying JSON decoding error, when present.

type AwaitChatArgs added in v2.37.0

type AwaitChatArgs struct {
	ChatID   string `json:"chat_id"`
	WaitSecs int    `json:"wait_secs"`
}

type AwaitChatResponse added in v2.37.0

type AwaitChatResponse struct {
	TimedOut bool           `json:"timed_out"`
	Chat     ChatToolStatus `json:"chat"`
}

type ChatModelConfigSummary added in v2.37.0

type ChatModelConfigSummary struct {
	ID          string `json:"id"`
	Model       string `json:"model"`
	DisplayName string `json:"display_name"`
	IsDefault   bool   `json:"is_default"`
}

type ChatToolFile added in v2.37.0

type ChatToolFile struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	MimeType  string    `json:"mime_type"`
	SizeBytes int64     `json:"size_bytes"`
	CreatedAt time.Time `json:"created_at"`
}

type ChatToolMessage added in v2.37.0

type ChatToolMessage struct {
	ID        int64                    `json:"id"`
	Role      codersdk.ChatMessageRole `json:"role"`
	CreatedAt time.Time                `json:"created_at"`
	Text      string                   `json:"text"`
	Files     []ChatToolMessageFile    `json:"files,omitempty"`
}

type ChatToolMessageFile added in v2.37.0

type ChatToolMessageFile struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	MimeType string `json:"mime_type"`
}

type ChatToolStatus added in v2.37.0

type ChatToolStatus struct {
	ID              string              `json:"id"`
	Title           string              `json:"title"`
	Status          codersdk.ChatStatus `json:"status"`
	Archived        bool                `json:"archived"`
	LastError       *codersdk.ChatError `json:"last_error,omitempty"`
	LastTurnSummary string              `json:"last_turn_summary,omitempty"`
	WorkspaceID     string              `json:"workspace_id,omitempty"`
	URL             string              `json:"url"`
	Labels          map[string]string   `json:"labels,omitempty"`
	Files           []ChatToolFile      `json:"files,omitempty"`
}

type CreateChatArgs added in v2.37.0

type CreateChatArgs struct {
	Prompt         string            `json:"prompt"`
	OrganizationID string            `json:"organization_id"`
	OwnerID        string            `json:"owner_id"`
	ModelConfigID  string            `json:"model_config_id"`
	Labels         map[string]string `json:"labels,omitempty"`
}

type CreateTemplateArgs

type CreateTemplateArgs struct {
	OrganizationID string `json:"organization_id"`
	Description    string `json:"description"`
	DisplayName    string `json:"display_name"`
	Icon           string `json:"icon"`
	Name           string `json:"name"`
	VersionID      string `json:"version_id"`
}

type CreateTemplateVersionArgs

type CreateTemplateVersionArgs struct {
	OrganizationID string `json:"organization_id"`
	FileID         string `json:"file_id"`
	TemplateID     string `json:"template_id"`
}

type CreateWorkspaceArgs

type CreateWorkspaceArgs struct {
	Name                    string            `json:"name"`
	RichParameters          map[string]string `json:"rich_parameters"`
	TemplateID              string            `json:"template_id,omitempty"`
	TemplateVersionID       string            `json:"template_version_id,omitempty"`
	TemplateVersionPresetID string            `json:"template_version_preset_id,omitempty"`
	User                    string            `json:"user,omitempty"`
}

type CreateWorkspaceBuildArgs

type CreateWorkspaceBuildArgs struct {
	RichParameters          map[string]string `json:"rich_parameters,omitempty"`
	TemplateVersionID       string            `json:"template_version_id"`
	TemplateVersionPresetID string            `json:"template_version_preset_id,omitempty"`
	Transition              string            `json:"transition"`
	WorkspaceID             string            `json:"workspace_id"`
}

type DeleteTemplateArgs

type DeleteTemplateArgs struct {
	TemplateID string `json:"template_id"`
}

type Deps

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

Deps provides access to tool dependencies.

func NewDeps

func NewDeps(client *codersdk.Client, opts ...func(*Deps)) (Deps, error)

func (Deps) ServerURL added in v2.26.0

func (d Deps) ServerURL() string

type DownloadChatFileArgs added in v2.37.0

type DownloadChatFileArgs struct {
	FileID   string `json:"file_id"`
	ChatID   string `json:"chat_id"`
	FileName string `json:"file_name"`
}

type DownloadChatFileResponse added in v2.37.0

type DownloadChatFileResponse struct {
	FileID    string    `json:"file_id"`
	Name      string    `json:"name"`
	MimeType  string    `json:"mime_type"`
	SizeBytes int64     `json:"size_bytes"`
	SHA256    string    `json:"sha256"`
	URL       string    `json:"url"`
	ExpiresAt time.Time `json:"expires_at"`
}

type FetchArgs added in v2.26.0

type FetchArgs struct {
	ID string `json:"id"`
}

type FetchResult added in v2.26.0

type FetchResult struct {
	ID       string            `json:"id"`
	Title    string            `json:"title"`
	Text     string            `json:"text"`
	URL      string            `json:"url"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

type GenericHandlerFunc

type GenericHandlerFunc func(context.Context, Deps, json.RawMessage) (json.RawMessage, error)

GenericHandlerFunc is a function that handles a tool call.

func WithCleanContext

func WithCleanContext(h GenericHandlerFunc) GenericHandlerFunc

WithCleanContext wraps a HandlerFunc to provide it with a new context. This ensures that no data is passed using context.Value. If a deadline is set on the parent context, it will be passed to the child context.

func WithRecover

WithRecover wraps a HandlerFunc to recover from panics and return an error.

type GenericTool

type GenericTool struct {
	aisdk.Tool
	Handler GenericHandlerFunc

	// MCPAnnotations are host hints used when this tool is exposed over MCP.
	MCPAnnotations MCPToolAnnotations

	// UserClientOptional indicates whether this tool can function without a valid
	// user authentication token. If true, the tool will be available even when
	// running in an unauthenticated mode with just an agent token.
	UserClientOptional bool
}

GenericTool is a type-erased wrapper for GenericTool. This allows referencing the tool without knowing the concrete argument or return type. The Handler function allows calling the tool with known types.

type GetChatArgs added in v2.37.0

type GetChatArgs struct {
	ChatID string `json:"chat_id"`
}

type GetChatMessagesArgs added in v2.37.0

type GetChatMessagesArgs struct {
	ChatID   string `json:"chat_id"`
	Limit    int    `json:"limit"`
	BeforeID int64  `json:"before_id"`
	AfterID  int64  `json:"after_id"`
}

type GetChatMessagesResponse added in v2.37.0

type GetChatMessagesResponse struct {
	Messages []ChatToolMessage `json:"messages"`
	HasMore  bool              `json:"has_more"`
	// Cursors come from the raw page so filtered pages remain traversable.
	NextBeforeID int64 `json:"next_before_id,omitempty"`
	NextAfterID  int64 `json:"next_after_id,omitempty"`
	// QueuedMessages is populated only on the initial page.
	QueuedMessages []string `json:"queued_messages,omitempty"`
}

type GetTemplateArgs added in v2.33.0

type GetTemplateArgs struct {
	TemplateID string `json:"template_id"`
}

type GetTemplateVersionLogsArgs

type GetTemplateVersionLogsArgs struct {
	TemplateVersionID string `json:"template_version_id"`
}

type GetWorkspaceAgentLogsArgs

type GetWorkspaceAgentLogsArgs struct {
	WorkspaceAgentID string `json:"workspace_agent_id"`
}

type GetWorkspaceArgs

type GetWorkspaceArgs struct {
	WorkspaceID string `json:"workspace_id"`
}

type GetWorkspaceBuildLogsArgs

type GetWorkspaceBuildLogsArgs struct {
	WorkspaceBuildID string `json:"workspace_build_id"`
}

type HandlerFunc

type HandlerFunc[Arg, Ret any] func(context.Context, Deps, Arg) (Ret, error)

HandlerFunc is a typed function that handles a tool call.

type InterruptChatArgs added in v2.37.0

type InterruptChatArgs struct {
	ChatID string `json:"chat_id"`
}

type ListChatModelConfigsArgs added in v2.37.0

type ListChatModelConfigsArgs struct {
	OrganizationID string `json:"organization_id"`
}

type ListChatModelConfigsResponse added in v2.37.0

type ListChatModelConfigsResponse struct {
	OrganizationID string                   `json:"organization_id"`
	ModelConfigs   []ChatModelConfigSummary `json:"model_configs"`
}

type ListChatsArgs added in v2.37.0

type ListChatsArgs struct {
	Labels map[string]string `json:"labels,omitempty"`
	Query  string            `json:"query"`
	Limit  int               `json:"limit"`
}

type ListChatsResponse added in v2.37.0

type ListChatsResponse struct {
	Chats []ChatToolStatus `json:"chats"`
}

type ListTemplateVersionParametersArgs

type ListTemplateVersionParametersArgs struct {
	TemplateVersionID string `json:"template_version_id"`
}

type ListWorkspacesArgs

type ListWorkspacesArgs struct {
	Owner string `json:"owner"`
}

type MCPToolAnnotations added in v2.32.0

type MCPToolAnnotations struct {
	ReadOnlyHint    bool
	DestructiveHint bool
	IdempotentHint  bool
	OpenWorldHint   bool
}

MCPToolAnnotations describes how an MCP host should classify a tool.

type MinimalTemplate

type MinimalTemplate struct {
	OrganizationID  string    `json:"organization_id"`
	DisplayName     string    `json:"display_name"`
	ID              string    `json:"id"`
	Name            string    `json:"name"`
	Description     string    `json:"description"`
	ActiveVersionID uuid.UUID `json:"active_version_id"`
	ActiveUserCount int       `json:"active_user_count"`
	AgentsAllowed   bool      `json:"agents_allowed"`
}

type MinimalWorkspace

type MinimalWorkspace struct {
	OrganizationID          string    `json:"organization_id"`
	ID                      string    `json:"id"`
	Name                    string    `json:"name"`
	TemplateID              string    `json:"template_id"`
	TemplateName            string    `json:"template_name"`
	TemplateDisplayName     string    `json:"template_display_name"`
	TemplateIcon            string    `json:"template_icon"`
	TemplateActiveVersionID uuid.UUID `json:"template_active_version_id"`
	Outdated                bool      `json:"outdated"`
}

type NoArgs

type NoArgs struct{}

NoArgs just represents an empty argument struct.

type ObjectID added in v2.26.0

type ObjectID struct {
	Type ObjectType
	ID   string
}

func (ObjectID) String added in v2.26.0

func (o ObjectID) String() string

type ObjectType added in v2.26.0

type ObjectType string
const (
	ObjectTypeTemplate  ObjectType = "template"
	ObjectTypeWorkspace ObjectType = "workspace"
)

type Prompt added in v2.37.0

type Prompt struct {
	Name        string
	Description string
	Arguments   []PromptArgument

	// RequiredTools lists the tools the rendered workflow cannot run
	// without; optional suggestions are excluded. Servers with a
	// restricted tool set should skip prompts whose required tools are
	// unavailable.
	RequiredTools []string

	Render func(args map[string]string) (string, error)
}

Prompt defines an MCP prompt shared by the HTTP and CLI servers. See https://modelcontextprotocol.io/specification/2026-07-28/server/prompts.

type PromptArgument added in v2.37.0

type PromptArgument struct {
	Name        string
	Description string
	Required    bool
}

PromptArgument describes one argument accepted by a Prompt.

type ReportTaskArgs

type ReportTaskArgs struct {
	Link    string `json:"link"`
	State   string `json:"state"`
	Summary string `json:"summary"`
}

type SearchArgs added in v2.26.0

type SearchArgs struct {
	Query string `json:"query"`
}

type SearchQuery added in v2.26.0

type SearchQuery struct {
	Type  SearchQueryType
	Query string
}

type SearchQueryType added in v2.26.0

type SearchQueryType string
const (
	SearchQueryTypeTemplates  SearchQueryType = "templates"
	SearchQueryTypeWorkspaces SearchQueryType = "workspaces"
)

type SearchResult added in v2.26.0

type SearchResult struct {
	Results []SearchResultItem `json:"results"`
}

type SearchResultItem added in v2.26.0

type SearchResultItem struct {
	ID    string `json:"id"`
	Title string `json:"title"`
	Text  string `json:"text"`
	URL   string `json:"url"`
}

type SendChatMessageArgs added in v2.37.0

type SendChatMessageArgs struct {
	ChatID       string                    `json:"chat_id"`
	Text         string                    `json:"text"`
	BusyBehavior codersdk.ChatBusyBehavior `json:"busy_behavior,omitempty"`
}

type SendChatMessageResponse added in v2.37.0

type SendChatMessageResponse struct {
	Queued   bool     `json:"queued"`
	Warnings []string `json:"warnings,omitempty"`
}

type TemplateDetail added in v2.33.0

type TemplateDetail struct {
	MinimalTemplate
	Parameters []codersdk.TemplateVersionParameter `json:"parameters"`
	Presets    []presetView                        `json:"presets,omitempty"`
}

TemplateDetail extends MinimalTemplate with the active version's rich parameters and presets. Presets are omitted when the template has none, to mirror the chattool read_template response shape.

type Tool

type Tool[Arg, Ret any] struct {
	aisdk.Tool
	Handler HandlerFunc[Arg, Ret]

	// MCPAnnotations is the shared source of truth for MCP tool
	// classification. Both the coderd-hosted MCP server and the CLI MCP
	// server translate these hints into mcp.Tool.Annotations so hosts can
	// consistently group tools.
	MCPAnnotations MCPToolAnnotations

	// UserClientOptional indicates whether this tool can function without a valid
	// user authentication token. If true, the tool will be available even when
	// running in an unauthenticated mode with just an agent token.
	UserClientOptional bool
}

Tool consists of an aisdk.Tool and a corresponding typed handler function.

func (Tool[Arg, Ret]) Generic

func (t Tool[Arg, Ret]) Generic() GenericTool

Generic returns a type-erased version of a TypedTool where the arguments and return values are converted to/from json.RawMessage. This allows the tool to be referenced without knowing the concrete arguments or return values. The original TypedHandlerFunc is wrapped to handle type conversion.

type UpdateTemplateActiveVersionArgs

type UpdateTemplateActiveVersionArgs struct {
	TemplateID        string `json:"template_id"`
	TemplateVersionID string `json:"template_version_id"`
}

type UploadTarFileArgs

type UploadTarFileArgs struct {
	Files map[string]string `json:"files"`
}

type WorkspaceBashArgs added in v2.25.0

type WorkspaceBashArgs struct {
	Workspace  string `json:"workspace"`
	Command    string `json:"command"`
	TimeoutMs  int    `json:"timeout_ms,omitempty"`
	Background bool   `json:"background,omitempty"`
}

type WorkspaceBashResult added in v2.25.0

type WorkspaceBashResult struct {
	Output   string `json:"output"`
	ExitCode int    `json:"exit_code"`
}

type WorkspaceEditFileArgs added in v2.27.0

type WorkspaceEditFileArgs struct {
	Workspace string                  `json:"workspace"`
	Path      string                  `json:"path"`
	Edits     []workspacesdk.FileEdit `json:"edits"`
}

type WorkspaceEditFilesArgs added in v2.27.0

type WorkspaceEditFilesArgs struct {
	Workspace string                   `json:"workspace"`
	Files     []workspacesdk.FileEdits `json:"files"`
}

type WorkspaceEditFilesResponse added in v2.33.0

type WorkspaceEditFilesResponse struct {
	Message string                        `json:"message"`
	Files   []workspacesdk.FileEditResult `json:"files,omitempty"`
}

WorkspaceEditFilesResponse is the response shape for the edit-file and edit-files tools. Message preserves the existing success text. Files carries the per-file results returned by the agent (populated when the agent-side IncludeDiff flag was set). The field is named Files (matching the agent's FileEditResponse.Files) so future per-file error or status fields can be added without a second wire break.

type WorkspaceLSArgs added in v2.27.0

type WorkspaceLSArgs struct {
	Workspace string `json:"workspace"`
	Path      string `json:"path"`
}

type WorkspaceLSFile added in v2.27.0

type WorkspaceLSFile struct {
	Path  string `json:"path"`
	IsDir bool   `json:"is_dir"`
}

type WorkspaceLSResponse added in v2.27.0

type WorkspaceLSResponse struct {
	Contents []WorkspaceLSFile `json:"contents"`
}

type WorkspaceListApp added in v2.28.0

type WorkspaceListApp struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}

type WorkspaceListAppsArgs added in v2.28.0

type WorkspaceListAppsArgs struct {
	Workspace string `json:"workspace"`
}

type WorkspaceListAppsResponse added in v2.28.0

type WorkspaceListAppsResponse struct {
	Apps []WorkspaceListApp `json:"apps"`
}

type WorkspacePortForwardArgs added in v2.27.0

type WorkspacePortForwardArgs struct {
	Workspace string `json:"workspace"`
	Port      int    `json:"port"`
}

type WorkspacePortForwardResponse added in v2.27.0

type WorkspacePortForwardResponse struct {
	URL string `json:"url"`
}

type WorkspaceReadFileArgs added in v2.27.0

type WorkspaceReadFileArgs struct {
	Workspace string `json:"workspace"`
	Path      string `json:"path"`
	Offset    int64  `json:"offset"`
	Limit     int64  `json:"limit"`
}

type WorkspaceReadFileResponse added in v2.27.0

type WorkspaceReadFileResponse struct {
	// Content is the base64-encoded bytes from the file.
	Content  []byte `json:"content"`
	MimeType string `json:"mimeType"`
}

type WorkspaceWriteFileArgs added in v2.27.0

type WorkspaceWriteFileArgs struct {
	Workspace string `json:"workspace"`
	Path      string `json:"path"`
	Content   []byte `json:"content"`
}

Jump to

Keyboard shortcuts

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