mcp

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2025 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package mcp implements the Model Context Protocol (MCP) server for OpenAI organization management. It provides a set of tools and resources for managing OpenAI projects, members, and usage statistics through a standardized protocol interface.

Server Configuration

The package provides a main entry point through NewMCPServer() which configures and returns an MCP server with the following capabilities:

  • Tool execution for organization management
  • Static and dynamic resource access
  • Real-time resource updates through subscriptions
  • Authentication token management
  • Logging and instrumentation

Resources

The package exposes several key resources through URI-based endpoints:

openai-orgs://active-projects    - Lists currently active projects
openai-orgs://current-members    - Shows current organization members
openai-orgs://usage-dashboard    - Displays usage statistics and metrics

Each resource supports pagination and optional real-time updates through subscriptions. Resource data is returned in specialized MIME types for proper content handling:

application/vnd.openai-orgs.project-list+json
application/vnd.openai-orgs.member-list+json
application/vnd.openai-orgs.usage+json

Tools

The package provides a comprehensive set of tools for direct organization management operations, including:

- Project management: list_projects, create_project, retrieve_project, modify_project, archive_project - Project user management: list_project_users, add_project_user, remove_project_user, retrieve_project_user, modify_project_user - Project API key management: list_project_api_keys, retrieve_project_api_key, delete_project_api_key - Project service account management: list_project_service_accounts, create_project_service_account, retrieve_project_service_account, delete_project_service_account - User management: list_users, retrieve_user, delete_user, modify_user_role - Invite management: list_invites, create_invite, retrieve_invite, delete_invite - Usage and billing statistics: get_usage

All tools are implemented using a generic handler and parameter schema pattern, ensuring consistent parameter validation, error handling, and testability. Parameters are registered with mcp.NewTool using type helpers (e.g., mcp.WithString, mcp.WithNumber, mcp.WithBoolean), making them visible and enforced in the MCP Inspector and compatible clients.

Tool Implementation Framework

- Tools use a GenericToolHandler that takes a ToolHandlerFunc and a ParamSchema, handling parameter extraction, validation, client instantiation, and result formatting. - Each tool defines its parameters using a ParamSchema and registers them with mcp.NewTool. - The framework is designed for testability, with support for dependency injection and GoMock-based mocks.

Resource Updates

Resources support real-time updates through a subscription mechanism. When a client subscribes to a resource, they receive updates when the underlying data changes:

  1. Active project status changes
  2. Member list modifications
  3. Usage statistics updates

The update frequency is managed by an internal polling mechanism that efficiently checks for changes in the underlying data.

Authentication

All operations require proper authentication through an OpenAI API token. The token is managed through context and is required for all tool and resource operations.

Example Usage

To create and start an MCP server:

server := mcp.NewMCPServer()
server.ServeStdio()

Resource subscriptions can be enabled through the subscription parameter:

{
	"uri": "openai-orgs://active-projects",
	"arguments": {
		"subscribe": true,
		"pagination": {
			"limit": 20,
			"after": "project_id"
		}
	}
}

Testing

- Unit tests for tool handlers use the standard Go testing package and GoMock for interface mocking. - The framework supports dependency injection for easier testability. - See llm-workbooks/mcp-tests.txt for the current test plan and coverage goals.

For more detailed information about specific components, refer to the individual type and function documentation.

Index

Constants

View Source
const (
	ResourceTemplateTypeProject               = "project"
	ResourceTemplateTypeMember                = "member"
	ResourceTemplateTypeUsage                 = "usage"
	ResourceTemplateTypeProjectServiceAccount = "project-service-account"

	MIMETypeProjectTemplate               = "application/vnd.openai-orgs.project+json"
	MIMETypeMemberTemplate                = "application/vnd.openai-orgs.member+json"
	MIMETypeUsageTemplate                 = "application/vnd.openai-orgs.usage+json"
	MIMETypeProjectServiceAccountTemplate = "application/vnd.openai-orgs.project-service-account+json"
)

Resource template types and MIME types

View Source
const (
	ResourceTypeActiveProjects = "active-projects"
	ResourceTypeCurrentMembers = "current-members"
	ResourceTypeUsageDashboard = "usage-dashboard"

	MIMETypeProjectList    = "application/vnd.openai-orgs.project-list+json"
	MIMETypeMemberList     = "application/vnd.openai-orgs.member-list+json"
	MIMETypeUsageDashboard = "application/vnd.openai-orgs.usage+json"
)

Resource types and MIME types

Variables

View Source
var (
	ErrNoAuthToken = errors.New("no auth token found in context")
	ErrEmptyToken  = errors.New("empty auth token provided")
)

Functions

func AddResourceTemplates

func AddResourceTemplates(s *server.MCPServer)

AddResourceTemplates adds resource template capabilities to the MCP server

func AddResources

func AddResources(s *server.MCPServer)

AddResources adds static resource capabilities to the MCP server

func AddTools

func AddTools(s *server.MCPServer)

func AuthFromEnvironment

func AuthFromEnvironment(c context.Context) context.Context

func GenericToolHandler added in v0.5.0

func GenericToolHandler(handler ToolHandlerFunc, paramSchema ParamSchema) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error)

GenericToolHandler wraps a ToolHandlerFunc for MCP Handles parameter extraction/validation, client instantiation, error handling, and result formatting

func NewMCPServer

func NewMCPServer() *server.MCPServer

Types

type ClientProvider

type ClientProvider interface {
	// NewClient creates a new OpenAI client with the given auth token
	NewClient(authToken string) *openaiorgs.Client
}

ClientProvider defines the interface for creating OpenAI clients

type DefaultClientProvider

type DefaultClientProvider struct{}

DefaultClientProvider implements the ClientProvider interface

func (*DefaultClientProvider) NewClient

func (p *DefaultClientProvider) NewClient(authToken string) *openaiorgs.Client

type ParamField added in v0.5.0

type ParamField struct {
	Name        string
	Required    bool
	Type        reflect.Kind
	Description string
	Enum        []any
}

ParamField defines a single parameter for a tool Name: parameter name Required: whether the parameter is mandatory Type: expected reflect.Kind (e.g., reflect.String) Description: human-readable description Enum: optional set of allowed values

type ParamSchema added in v0.5.0

type ParamSchema struct {
	Fields []ParamField
}

ParamSchema defines the schema for tool parameters Fields: list of parameter fields

func (*ParamSchema) ExtractAndValidate added in v0.5.0

func (ps *ParamSchema) ExtractAndValidate(req mcp.CallToolRequest) (map[string]any, error)

ExtractAndValidate extracts and validates parameters from a CallToolRequest Returns a map of validated parameters or an error if validation fails

func (*ParamSchema) ToMCPParameterSchema added in v0.5.0

func (ps *ParamSchema) ToMCPParameterSchema() map[string]any

ToMCPParameterSchema converts ParamSchema to a JSON Schema-like map for MCP

type ResourceHandler

type ResourceHandler func(context.Context, mcp.ReadResourceRequest) ([]mcp.ResourceContents, error)

ResourceHandler is a function type that handles resource requests

type ResourceManager

type ResourceManager interface {
	// AddResource adds a new resource to the MCP server
	AddResource(resource *mcp.Resource, handler ResourceHandler)

	// ListResources returns all registered resources
	ListResources() []*mcp.Resource
}

ResourceManager defines the interface for managing MCP resources

type ResourceProvider

type ResourceProvider interface {
	// GetResource retrieves a resource by its URI and parameters
	GetResource(ctx context.Context, uri string, params map[string]any) (any, error)

	// Subscribe subscribes to updates for a resource
	Subscribe(uri string) (<-chan mcp.ResourceContents, func())
}

ResourceProvider defines the interface for providing MCP resources

type ResourceURI

type ResourceURI struct {
	Type           string
	ProjectID      string
	ServiceAccount string
	MemberID       string
}

ResourceURI represents a parsed OpenAI organizations URI

func ParseURI

func ParseURI(uri string) (*ResourceURI, error)

ParseURI parses a raw URI string into a structured ResourceURI

func (*ResourceURI) String

func (r *ResourceURI) String() string

String converts the ResourceURI back to its string representation

type SubscriptionHandler

type SubscriptionHandler func(contents mcp.ResourceContents)

SubscriptionHandler is a function type that handles subscription updates

type SubscriptionManager

type SubscriptionManager interface {
	// Subscribe creates a new subscription for the given URI
	Subscribe(uri string) chan mcp.ResourceContents

	// Unsubscribe removes a subscription
	Unsubscribe(uri string, ch chan mcp.ResourceContents)

	// Notify notifies all subscribers of a resource update
	Notify(uri string, contents mcp.ResourceContents)
}

SubscriptionManager defines the interface for managing resource subscriptions

type SubscriptionOptions

type SubscriptionOptions struct {
	// BufferSize is the size of the channel buffer (default 1)
	BufferSize int
	// Handler is called for each update (optional)
	Handler SubscriptionHandler
}

SubscriptionOptions contains options for creating a subscription

func DefaultSubscriptionOptions

func DefaultSubscriptionOptions() *SubscriptionOptions

DefaultSubscriptionOptions returns the default subscription options

func (*SubscriptionOptions) WithBufferSize

func (o *SubscriptionOptions) WithBufferSize(size int) *SubscriptionOptions

WithBufferSize sets the channel buffer size

func (*SubscriptionOptions) WithHandler

WithHandler sets the update handler

type ToolHandlerFunc added in v0.5.0

type ToolHandlerFunc func(ctx context.Context, client *openaiorgs.Client, params map[string]any) (any, error)

ToolHandlerFunc is a generic handler signature for MCP tools ctx: context, client: OpenAI orgs client, params: validated parameters Returns: result (any) and error

Jump to

Keyboard shortcuts

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