contextforge

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2025 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package contextforge provides a Go client library for the IBM ContextForge MCP Gateway API.

ContextForge is a feature-rich gateway, proxy, and MCP Registry that federates MCP and REST services. It acts as a unified endpoint for AI clients, consolidating discovery, authentication, rate-limiting, observability, and virtual server management. This client library provides an idiomatic Go interface to the ContextForge API, following architectural patterns established by popular Go libraries like google/go-github.

Features

The SDK provides full CRUD operations for ContextForge resources:

  • Manage tools with create, update, delete, and toggle operations
  • Manage resources with URI-based access and template support
  • Manage gateways for MCP server federation and proxying
  • Manage servers including virtual MCP servers with association endpoints
  • Manage prompts with template-based AI interactions
  • Manage A2A agents with agent-to-agent protocol support and invocation
  • Cursor-based pagination (Tools, Resources, Gateways, Servers, Prompts)
  • Skip/limit pagination (Agents)
  • Rate limit tracking from response headers
  • Context support for all API calls
  • Bearer token (JWT) authentication
  • Comprehensive error handling

Authentication

The ContextForge API uses Bearer token (JWT) authentication. You must provide a valid JWT token when creating the client:

client, err := contextforge.NewClient(nil, "http://localhost:8000/", "your-jwt-token")
if err != nil {
	log.Fatal(err)
}

Usage

Import the package:

import "github.com/leefowlercu/go-contextforge/contextforge"

Create a new client (use SuggestedBaseURL for local development):

client, err := contextforge.NewClient(nil, contextforge.SuggestedBaseURL, "your-jwt-token")
if err != nil {
	log.Fatal(err)
}

Create a client with custom base URL:

client, err := contextforge.NewClient(nil, "https://contextforge.example.com/", "your-jwt-token")
if err != nil {
	log.Fatal(err)
}

You can provide a custom HTTP client for advanced configuration:

httpClient := &http.Client{
	Timeout: 60 * time.Second,
}
client, err := contextforge.NewClient(httpClient, contextforge.SuggestedBaseURL, "your-jwt-token")
if err != nil {
	log.Fatal(err)
}

List tools:

tools, resp, err := client.Tools.List(context.Background(), nil)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Found %d tools\n", len(tools))

List tools with filtering:

opts := &contextforge.ToolListOptions{
	IncludeInactive: false,
	Tags: "automation,api",
	Visibility: "public",
	ListOptions: contextforge.ListOptions{
		Limit: 20,
	},
}
tools, resp, err := client.Tools.List(context.Background(), opts)

Get a specific tool:

tool, resp, err := client.Tools.Get(context.Background(), "tool-id")

Create a new tool:

newTool := &contextforge.Tool{
	Name: "my-tool",
	Description: contextforge.String("A custom tool"),
	InputSchema: map[string]any{
		"type": "object",
		"properties": map[string]any{
			"input": map[string]any{"type": "string"},
		},
	},
	Enabled: true,
}
created, resp, err := client.Tools.Create(context.Background(), newTool, nil)

Update a tool:

tool.Description = contextforge.String("Updated description")
updated, resp, err := client.Tools.Update(context.Background(), "tool-id", tool)

Toggle a tool's status:

toggled, resp, err := client.Tools.Toggle(context.Background(), "tool-id", true)

Delete a tool:

resp, err := client.Tools.Delete(context.Background(), "tool-id")

Pagination

The API supports two pagination patterns:

Cursor-based pagination (Tools, Resources, Gateways, Servers, Prompts):

var allTools []*contextforge.Tool
opts := &contextforge.ToolListOptions{
	ListOptions: contextforge.ListOptions{Limit: 50},
}

for {
	tools, resp, err := client.Tools.List(context.Background(), opts)
	if err != nil {
		break
	}
	allTools = append(allTools, tools...)

	if resp.NextCursor == "" {
		break
	}
	opts.Cursor = resp.NextCursor
}

Skip/limit (offset-based) pagination (Agents only):

var allAgents []*contextforge.Agent
opts := &contextforge.AgentListOptions{
	Limit: 50,
}

for skip := 0; ; skip += opts.Limit {
	opts.Skip = skip
	agents, _, err := client.Agents.List(context.Background(), opts)
	if err != nil {
		break
	}
	allAgents = append(allAgents, agents...)

	if len(agents) < opts.Limit {
		break
	}
}

Error Handling

The library provides structured error handling with custom error types:

tools, resp, err := client.Tools.List(context.Background(), nil)
if err != nil {
	if rateLimitErr, ok := err.(*contextforge.RateLimitError); ok {
		fmt.Printf("Rate limited. Reset at: %v\n", rateLimitErr.Rate.Reset)
		return
	}
	if apiErr, ok := err.(*contextforge.ErrorResponse); ok {
		fmt.Printf("API error: %v\n", apiErr.Message)
		return
	}
	log.Fatal(err)
}

Rate Limiting

Rate limit information is tracked and available in response objects:

tools, resp, err := client.Tools.List(context.Background(), nil)
if err == nil && resp.Rate.Limit > 0 {
	fmt.Printf("Rate Limit: %d/%d remaining\n",
		resp.Rate.Remaining, resp.Rate.Limit)
	fmt.Printf("Reset at: %v\n", resp.Rate.Reset)
}

Service Architecture

The client follows a service-oriented architecture where different API endpoints are organized into service structs:

// Available services
client.Tools      // Tool-related operations
client.Resources  // Resource-related operations
client.Gateways   // Gateway-related operations
client.Servers    // Server-related operations
client.Prompts    // Prompt-related operations
client.Agents     // A2A agent-related operations

Each service provides methods for different operations. Most services follow a common CRUD pattern:

// Common CRUD methods (most services)
List(ctx, opts) ([]*Type, *Response, error)
Get(ctx, id) (*Type, *Response, error)
Create(ctx, item, opts) (*Type, *Response, error)  // opts is optional
Update(ctx, id, item) (*Type, *Response, error)
Delete(ctx, id) (*Response, error)
Toggle(ctx, id, activate) (*Type, *Response, error)

Some services have unique methods:

// ServersService association endpoints
client.Servers.ListTools(ctx, serverID, opts)
client.Servers.ListResources(ctx, serverID, opts)
client.Servers.ListPrompts(ctx, serverID, opts)

// ResourcesService template support
client.Resources.ListTemplates(ctx)

// AgentsService invocation
client.Agents.Invoke(ctx, agentName, req)  // Uses name, not ID

Helper Functions

The package provides helper functions for working with pointer types, following Go API conventions:

contextforge.String("value")    // Returns *string
contextforge.Int(42)            // Returns *int
contextforge.Bool(true)         // Returns *bool
contextforge.Time(t)            // Returns *time.Time

contextforge.StringValue(ptr)   // Returns string value or ""
contextforge.IntValue(ptr)      // Returns int value or 0
contextforge.BoolValue(ptr)     // Returns bool value or false
contextforge.TimeValue(ptr)     // Returns time.Time value or zero time

See Also

Related resources:

Index

Constants

View Source
const (
	// SuggestedBaseURL is the default base URL for a locally-running ContextForge instance.
	// Users should provide their own base URL when creating clients.
	SuggestedBaseURL = "http://localhost:8000/"
)
View Source
const Version = "0.3.0"

Version is the current release version of the go-contextforge SDK. This version is included in the User-Agent header for all API requests.

Variables

This section is empty.

Functions

func Bool

func Bool(v bool) *bool

Bool returns a pointer to the provided bool value.

func BoolValue

func BoolValue(v *bool) bool

BoolValue returns the value of the bool pointer passed in or false if the pointer is nil.

func CheckResponse

func CheckResponse(r *http.Response) error

CheckResponse checks the API response for errors, and returns them if present. A response is considered an error if it has a status code outside the 200 range. API error responses are expected to have either no response body, or a JSON response body that maps to ErrorResponse.

func Int

func Int(v int) *int

Int returns a pointer to the provided int value.

func IntValue

func IntValue(v *int) int

IntValue returns the value of the int pointer passed in or 0 if the pointer is nil.

func String

func String(v string) *string

String returns a pointer to the provided string value.

func StringValue

func StringValue(v *string) string

StringValue returns the value of the string pointer passed in or "" if the pointer is nil.

func Time

func Time(v time.Time) *time.Time

Time returns a pointer to the provided time.Time value.

func TimeValue

func TimeValue(v *time.Time) time.Time

TimeValue returns the value of the time.Time pointer passed in or the zero time if the pointer is nil.

Types

type Agent added in v0.2.0

type Agent struct {
	// Core fields
	ID              string         `json:"id"`
	Name            string         `json:"name"`
	Slug            string         `json:"slug"`
	Description     *string        `json:"description,omitempty"`
	EndpointURL     string         `json:"endpointUrl"`
	AgentType       string         `json:"agentType"`
	ProtocolVersion string         `json:"protocolVersion"`
	Capabilities    map[string]any `json:"capabilities,omitempty"`
	Config          map[string]any `json:"config,omitempty"`
	AuthType        *string        `json:"authType,omitempty"`
	Enabled         bool           `json:"enabled"`
	Reachable       bool           `json:"reachable"`

	// Timestamps
	CreatedAt       *Timestamp `json:"createdAt,omitempty"`
	UpdatedAt       *Timestamp `json:"updatedAt,omitempty"`
	LastInteraction *Timestamp `json:"lastInteraction,omitempty"`

	// Organizational fields
	Tags       []string      `json:"tags,omitempty"`
	Metrics    *AgentMetrics `json:"metrics,omitempty"`
	TeamID     *string       `json:"teamId,omitempty"`
	OwnerEmail *string       `json:"ownerEmail,omitempty"`
	Visibility *string       `json:"visibility,omitempty"`

	// Metadata fields (read-only)
	CreatedBy         *string `json:"createdBy,omitempty"`
	CreatedFromIP     *string `json:"createdFromIp,omitempty"`
	CreatedVia        *string `json:"createdVia,omitempty"`
	CreatedUserAgent  *string `json:"createdUserAgent,omitempty"`
	ModifiedBy        *string `json:"modifiedBy,omitempty"`
	ModifiedFromIP    *string `json:"modifiedFromIp,omitempty"`
	ModifiedVia       *string `json:"modifiedVia,omitempty"`
	ModifiedUserAgent *string `json:"modifiedUserAgent,omitempty"`
	ImportBatchID     *string `json:"importBatchId,omitempty"`
	FederationSource  *string `json:"federationSource,omitempty"`
	Version           *int    `json:"version,omitempty"`
}

Agent represents an A2A (Agent-to-Agent) agent in the ContextForge API. A2A agents enable inter-agent communication using the ContextForge A2A protocol.

type AgentCreate added in v0.2.0

type AgentCreate struct {
	// Required fields
	Name        string `json:"name"`
	EndpointURL string `json:"endpoint_url"`

	// Optional core fields
	Slug            *string        `json:"slug,omitempty"`
	Description     *string        `json:"description,omitempty"`
	AgentType       string         `json:"agent_type,omitempty"`       // default: "generic"
	ProtocolVersion string         `json:"protocol_version,omitempty"` // default: "1.0"
	Capabilities    map[string]any `json:"capabilities,omitempty"`
	Config          map[string]any `json:"config,omitempty"`

	// Authentication fields
	AuthType  *string `json:"auth_type,omitempty"`
	AuthValue *string `json:"auth_value,omitempty"` // Will be encrypted by API

	// Organizational fields (snake_case)
	Tags       []string `json:"tags,omitempty"`
	TeamID     *string  `json:"team_id,omitempty"`
	OwnerEmail *string  `json:"owner_email,omitempty"`
	Visibility *string  `json:"visibility,omitempty"` // default: "public"
}

AgentCreate represents the request body for creating an A2A agent. Note: Uses snake_case field names as required by the API.

type AgentCreateOptions added in v0.2.0

type AgentCreateOptions struct {
	TeamID     *string
	Visibility *string
}

AgentCreateOptions specifies additional options for creating an agent. These fields are placed at the top level of the request wrapper.

type AgentInvokeRequest added in v0.2.0

type AgentInvokeRequest struct {
	Parameters      map[string]any `json:"parameters,omitempty"`
	InteractionType string         `json:"interaction_type,omitempty"` // default: "query"
}

AgentInvokeRequest represents the request body for invoking an A2A agent.

type AgentListOptions added in v0.2.0

type AgentListOptions struct {
	// Skip specifies the number of items to skip (offset)
	Skip int `url:"skip,omitempty"`

	// Limit specifies the maximum number of items to return (max: 1000, default: 100)
	Limit int `url:"limit,omitempty"`

	// IncludeInactive includes inactive agents in the results
	IncludeInactive bool `url:"include_inactive,omitempty"`

	// Tags filters agents by tags (comma-separated)
	Tags string `url:"tags,omitempty"`

	// TeamID filters agents by team ID
	TeamID string `url:"team_id,omitempty"`

	// Visibility filters agents by visibility (public, private, etc.)
	Visibility string `url:"visibility,omitempty"`
}

AgentListOptions specifies the optional parameters to the AgentsService.List method. Note: Agents use skip/limit (offset-based) pagination instead of cursor-based.

type AgentMetrics added in v0.2.0

type AgentMetrics struct {
	TotalExecutions      int        `json:"totalExecutions"`
	SuccessfulExecutions int        `json:"successfulExecutions"`
	FailedExecutions     int        `json:"failedExecutions"`
	FailureRate          float64    `json:"failureRate"`
	MinResponseTime      *float64   `json:"minResponseTime,omitempty"`
	MaxResponseTime      *float64   `json:"maxResponseTime,omitempty"`
	AvgResponseTime      *float64   `json:"avgResponseTime,omitempty"`
	LastExecutionTime    *Timestamp `json:"lastExecutionTime,omitempty"`
}

AgentMetrics represents performance statistics for an agent.

type AgentUpdate added in v0.2.0

type AgentUpdate struct {
	// All fields optional (camelCase per API spec)
	Name            *string        `json:"name,omitempty"`
	Description     *string        `json:"description,omitempty"`
	EndpointURL     *string        `json:"endpointUrl,omitempty"`
	AgentType       *string        `json:"agentType,omitempty"`
	ProtocolVersion *string        `json:"protocolVersion,omitempty"`
	Capabilities    map[string]any `json:"capabilities,omitempty"`
	Config          map[string]any `json:"config,omitempty"`
	AuthType        *string        `json:"authType,omitempty"`
	AuthValue       *string        `json:"authValue,omitempty"`
	Tags            []string       `json:"tags,omitempty"`
	TeamID          *string        `json:"teamId,omitempty"`
	OwnerEmail      *string        `json:"ownerEmail,omitempty"`
	Visibility      *string        `json:"visibility,omitempty"`
}

AgentUpdate represents the request body for updating an agent. Note: Uses camelCase field names as required by the API.

type AgentsService added in v0.2.0

type AgentsService service

AgentsService handles communication with the A2A agent related methods of the ContextForge API.

func (*AgentsService) Create added in v0.2.0

func (s *AgentsService) Create(ctx context.Context, agent *AgentCreate, opts *AgentCreateOptions) (*Agent, *Response, error)

Create creates a new A2A agent. The opts parameter allows setting team_id and visibility at the request wrapper level.

func (*AgentsService) Delete added in v0.2.0

func (s *AgentsService) Delete(ctx context.Context, agentID string) (*Response, error)

Delete deletes an agent by ID.

func (*AgentsService) Get added in v0.2.0

func (s *AgentsService) Get(ctx context.Context, agentID string) (*Agent, *Response, error)

Get retrieves a specific agent by its ID.

func (*AgentsService) Invoke added in v0.2.0

func (s *AgentsService) Invoke(ctx context.Context, agentName string, req *AgentInvokeRequest) (map[string]any, *Response, error)

Invoke invokes an A2A agent by name with specified parameters. Note: Uses agent name (not ID) as identifier. The req parameter is optional; pass nil to use default parameters.

func (*AgentsService) List added in v0.2.0

func (s *AgentsService) List(ctx context.Context, opts *AgentListOptions) ([]*Agent, *Response, error)

List retrieves a paginated list of agents from the ContextForge API. Note: Agents use skip/limit (offset-based) pagination instead of cursor-based.

func (*AgentsService) Toggle added in v0.2.0

func (s *AgentsService) Toggle(ctx context.Context, agentID string, activate bool) (*Agent, *Response, error)

Toggle toggles an agent's enabled status. The activate parameter determines whether to enable (true) or disable (false) the agent.

func (*AgentsService) Update added in v0.2.0

func (s *AgentsService) Update(ctx context.Context, agentID string, agent *AgentUpdate) (*Agent, *Response, error)

Update updates an existing agent. Note: The API does not wrap the request body for agent updates.

type Client

type Client struct {

	// Base URL for API requests.
	// Defaults to http://localhost:8000/, but can be
	// overridden to point to another ContextForge instance.
	BaseURL *url.URL

	// User agent used when communicating with the ContextForge API.
	UserAgent string

	// Bearer token (JWT) for API authentication
	BearerToken string

	// Services used for talking to different parts of the ContextForge API
	Tools     *ToolsService
	Resources *ResourcesService
	Gateways  *GatewaysService
	Servers   *ServersService
	Prompts   *PromptsService
	Agents    *AgentsService
	// contains filtered or unexported fields
}

Client manages communication with the ContextForge MCP Gateway API.

func NewClient

func NewClient(httpClient *http.Client, baseURL string, bearerToken string) (*Client, error)

NewClient returns a new ContextForge API client with the specified base URL. If a nil httpClient is provided, a new http.Client will be used. The bearerToken parameter is required for API authentication and should be a valid JWT token. The baseURL parameter must be a valid URL; a trailing slash will be added automatically if missing.

func (*Client) Do

func (c *Client) Do(ctx context.Context, req *http.Request, v any) (*Response, error)

Do sends an API request and returns the API response. The API response is JSON decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred. If v implements the io.Writer interface, the raw response body will be written to v, without attempting to first decode it.

The provided ctx must be non-nil. If it is canceled or times out, ctx.Err() will be returned.

func (*Client) NewRequest

func (c *Client) NewRequest(method, urlStr string, body any) (*http.Request, error)

NewRequest creates an API request. A relative URL can be provided in urlStr, in which case it is resolved relative to the BaseURL of the Client. Relative URLs should always be specified without a preceding slash. If specified, the value pointed to by body is JSON encoded and included as the request body.

type Error

type Error struct {
	Resource string `json:"resource,omitempty"` // Resource on which the error occurred
	Field    string `json:"field,omitempty"`    // Field on which the error occurred
	Code     string `json:"code,omitempty"`     // Validation error code
	Message  string `json:"message,omitempty"`  // Message describing the error
}

Error represents a single error detail in an API response.

type ErrorResponse

type ErrorResponse struct {
	Response *http.Response // HTTP response that caused this error
	Message  string         `json:"message,omitempty"`
	Errors   []Error        `json:"errors,omitempty"`
}

ErrorResponse represents an error response from the ContextForge API.

func (*ErrorResponse) Error

func (r *ErrorResponse) Error() string

type FlexibleID

type FlexibleID string

FlexibleID represents an ID that can be either a string or integer from the API. The ContextForge API inconsistently returns IDs as integers in some responses (e.g., CREATE) and as strings in others (e.g., GET). This type handles both cases.

func (FlexibleID) String

func (f FlexibleID) String() string

String returns the string representation of the ID.

func (*FlexibleID) UnmarshalJSON

func (f *FlexibleID) UnmarshalJSON(data []byte) error

UnmarshalJSON handles both string and integer ID values from the API.

type Gateway

type Gateway struct {
	// Core fields
	ID           *string        `json:"id,omitempty"`
	Name         string         `json:"name"`
	URL          string         `json:"url"`
	Description  *string        `json:"description,omitempty"`
	Transport    string         `json:"transport,omitempty"`
	Enabled      bool           `json:"enabled,omitempty"`
	Reachable    bool           `json:"reachable,omitempty"`
	Capabilities map[string]any `json:"capabilities,omitempty"`

	// Authentication fields
	PassthroughHeaders []string            `json:"passthroughHeaders,omitempty"`
	AuthType           *string             `json:"authType,omitempty"`
	AuthUsername       *string             `json:"authUsername,omitempty"`
	AuthPassword       *string             `json:"authPassword,omitempty"`
	AuthToken          *string             `json:"authToken,omitempty"`
	AuthHeaderKey      *string             `json:"authHeaderKey,omitempty"`
	AuthHeaderValue    *string             `json:"authHeaderValue,omitempty"`
	AuthHeaders        []map[string]string `json:"authHeaders,omitempty"`
	AuthValue          *string             `json:"authValue,omitempty"`
	OAuthConfig        map[string]any      `json:"oauthConfig,omitempty"`

	// Organizational fields
	Tags       []string `json:"tags,omitempty"`
	TeamID     *string  `json:"teamId,omitempty"`
	Team       *string  `json:"team,omitempty"`
	OwnerEmail *string  `json:"ownerEmail,omitempty"`
	Visibility *string  `json:"visibility,omitempty"`

	// Timestamps
	CreatedAt *Timestamp `json:"createdAt,omitempty"`
	UpdatedAt *Timestamp `json:"updatedAt,omitempty"`
	LastSeen  *Timestamp `json:"lastSeen,omitempty"`

	// Metadata fields (read-only)
	CreatedBy         *string `json:"createdBy,omitempty"`
	CreatedFromIP     *string `json:"createdFromIp,omitempty"`
	CreatedVia        *string `json:"createdVia,omitempty"`
	CreatedUserAgent  *string `json:"createdUserAgent,omitempty"`
	ModifiedBy        *string `json:"modifiedBy,omitempty"`
	ModifiedFromIP    *string `json:"modifiedFromIp,omitempty"`
	ModifiedVia       *string `json:"modifiedVia,omitempty"`
	ModifiedUserAgent *string `json:"modifiedUserAgent,omitempty"`
	ImportBatchID     *string `json:"importBatchId,omitempty"`
	FederationSource  *string `json:"federationSource,omitempty"`
	Version           *int    `json:"version,omitempty"`
	Slug              *string `json:"slug,omitempty"`
}

Gateway represents a ContextForge gateway.

type GatewayCreateOptions

type GatewayCreateOptions struct {
	TeamID     *string
	Visibility *string
}

GatewayCreateOptions specifies additional options for creating a gateway. These fields are placed at the top level of the request wrapper.

type GatewayListOptions

type GatewayListOptions struct {
	ListOptions

	// IncludeInactive includes inactive gateways in the results
	IncludeInactive bool `url:"include_inactive,omitempty"`
}

GatewayListOptions specifies the optional parameters to the GatewaysService.List method.

type GatewaysService

type GatewaysService service

GatewaysService handles communication with the gateway related methods of the ContextForge API.

func (*GatewaysService) Create

func (s *GatewaysService) Create(ctx context.Context, gateway *Gateway, opts *GatewayCreateOptions) (*Gateway, *Response, error)

Create creates a new gateway. The opts parameter allows setting team_id and visibility fields. Note: Unlike other services, gateway creation does NOT wrap the gateway object.

func (*GatewaysService) Delete

func (s *GatewaysService) Delete(ctx context.Context, gatewayID string) (*Response, error)

Delete deletes a gateway by its ID.

func (*GatewaysService) Get

func (s *GatewaysService) Get(ctx context.Context, gatewayID string) (*Gateway, *Response, error)

Get retrieves a specific gateway by its ID.

func (*GatewaysService) List

List retrieves a list of gateways from the ContextForge API.

func (*GatewaysService) Toggle

func (s *GatewaysService) Toggle(ctx context.Context, gatewayID string, activate bool) (*Gateway, *Response, error)

Toggle toggles a gateway's enabled status.

func (*GatewaysService) Update

func (s *GatewaysService) Update(ctx context.Context, gatewayID string, gateway *Gateway) (*Gateway, *Response, error)

Update updates an existing gateway.

type ListOptions

type ListOptions struct {
	// Limit specifies the maximum number of items to return.
	// The API may return fewer than this value.
	Limit int `url:"limit,omitempty"`

	// Cursor is an opaque string used for pagination.
	// To get the next page of results, pass the NextCursor from the
	// previous response.
	Cursor string `url:"cursor,omitempty"`
}

ListOptions specifies the optional parameters to various List methods that support pagination.

type ListResourceTemplatesResult

type ListResourceTemplatesResult struct {
	Templates []ResourceTemplate `json:"templates"`
}

ListResourceTemplatesResult represents the response from listing resource templates.

type Prompt

type Prompt struct {
	// Core fields
	ID          int              `json:"id"`
	Name        string           `json:"name"`
	Description *string          `json:"description,omitempty"`
	Template    string           `json:"template"`
	Arguments   []PromptArgument `json:"arguments"`
	CreatedAt   *Timestamp       `json:"createdAt,omitempty"`
	UpdatedAt   *Timestamp       `json:"updatedAt,omitempty"`
	IsActive    bool             `json:"isActive"`
	Tags        []string         `json:"tags,omitempty"`
	Metrics     *PromptMetrics   `json:"metrics,omitempty"`

	// Organizational fields
	TeamID     *string `json:"teamId,omitempty"`
	Team       *string `json:"team,omitempty"`
	OwnerEmail *string `json:"ownerEmail,omitempty"`
	Visibility *string `json:"visibility,omitempty"`

	// Metadata fields (read-only)
	CreatedBy         *string `json:"createdBy,omitempty"`
	CreatedFromIP     *string `json:"createdFromIp,omitempty"`
	CreatedVia        *string `json:"createdVia,omitempty"`
	CreatedUserAgent  *string `json:"createdUserAgent,omitempty"`
	ModifiedBy        *string `json:"modifiedBy,omitempty"`
	ModifiedFromIP    *string `json:"modifiedFromIp,omitempty"`
	ModifiedVia       *string `json:"modifiedVia,omitempty"`
	ModifiedUserAgent *string `json:"modifiedUserAgent,omitempty"`
	ImportBatchID     *string `json:"importBatchId,omitempty"`
	FederationSource  *string `json:"federationSource,omitempty"`
	Version           *int    `json:"version,omitempty"`
}

Prompt represents a ContextForge prompt (read response). Note: These types are shared between ServersService and the future PromptsService.

type PromptArgument

type PromptArgument struct {
	Name        string  `json:"name"`
	Description *string `json:"description,omitempty"`
	Required    bool    `json:"required,omitempty"`
}

PromptArgument represents a parameter definition for a prompt.

type PromptCreate

type PromptCreate struct {
	Name        string           `json:"name"`
	Description *string          `json:"description,omitempty"`
	Template    string           `json:"template"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
	Tags        []string         `json:"tags,omitempty"`

	// Organizational fields (snake_case per API spec)
	TeamID     *string `json:"team_id,omitempty"`
	OwnerEmail *string `json:"owner_email,omitempty"`
	Visibility *string `json:"visibility,omitempty"`
}

PromptCreate represents the request body for creating a prompt. Note: Uses snake_case field names as required by the API.

type PromptCreateOptions

type PromptCreateOptions struct {
	TeamID     *string
	Visibility *string
}

PromptCreateOptions specifies additional options for creating a prompt. These fields are placed at the top level of the request wrapper.

type PromptListOptions

type PromptListOptions struct {
	ListOptions

	// IncludeInactive includes inactive prompts in the results
	IncludeInactive bool `url:"include_inactive,omitempty"`

	// Tags filters prompts by tags (comma-separated)
	Tags string `url:"tags,omitempty"`

	// TeamID filters prompts by team ID
	TeamID string `url:"team_id,omitempty"`

	// Visibility filters prompts by visibility (public, private, etc.)
	Visibility string `url:"visibility,omitempty"`
}

PromptListOptions specifies the optional parameters to the PromptsService.List method.

type PromptMetrics

type PromptMetrics struct {
	TotalExecutions      int        `json:"totalExecutions"`
	SuccessfulExecutions int        `json:"successfulExecutions"`
	FailedExecutions     int        `json:"failedExecutions"`
	FailureRate          float64    `json:"failureRate"`
	MinResponseTime      *float64   `json:"minResponseTime,omitempty"`
	MaxResponseTime      *float64   `json:"maxResponseTime,omitempty"`
	AvgResponseTime      *float64   `json:"avgResponseTime,omitempty"`
	LastExecutionTime    *Timestamp `json:"lastExecutionTime,omitempty"`
}

PromptMetrics represents performance statistics for a prompt.

type PromptUpdate

type PromptUpdate struct {
	Name        *string          `json:"name,omitempty"`
	Description *string          `json:"description,omitempty"`
	Template    *string          `json:"template,omitempty"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
	Tags        []string         `json:"tags,omitempty"`

	// Organizational fields (camelCase per API spec)
	TeamID     *string `json:"teamId,omitempty"`
	OwnerEmail *string `json:"ownerEmail,omitempty"`
	Visibility *string `json:"visibility,omitempty"`
}

PromptUpdate represents the request body for updating a prompt. Note: Uses camelCase field names as required by the API.

type PromptsService

type PromptsService service

PromptsService handles communication with the prompt related methods of the ContextForge API.

func (*PromptsService) Create

func (s *PromptsService) Create(ctx context.Context, prompt *PromptCreate, opts *PromptCreateOptions) (*Prompt, *Response, error)

Create creates a new prompt. The opts parameter allows setting team_id and visibility at the request wrapper level.

func (*PromptsService) Delete

func (s *PromptsService) Delete(ctx context.Context, promptID int) (*Response, error)

Delete deletes a prompt by its ID.

func (*PromptsService) List

func (s *PromptsService) List(ctx context.Context, opts *PromptListOptions) ([]*Prompt, *Response, error)

List retrieves a paginated list of prompts from the ContextForge API.

func (*PromptsService) Toggle

func (s *PromptsService) Toggle(ctx context.Context, promptID int, activate bool) (*Prompt, *Response, error)

Toggle toggles a prompt's active status.

func (*PromptsService) Update

func (s *PromptsService) Update(ctx context.Context, promptID int, prompt *PromptUpdate) (*Prompt, *Response, error)

Update updates an existing prompt. Note: The API does not wrap the request body for prompt updates.

type Rate

type Rate struct {
	// The maximum number of requests that can be made in the current window.
	Limit int

	// The number of requests remaining in the current window.
	Remaining int

	// The time at which the current rate limit window resets.
	Reset time.Time
}

Rate represents the rate limit information returned in API responses.

type RateLimitError

type RateLimitError struct {
	Rate     Rate           // Rate specifies the current rate limit information
	Response *http.Response // HTTP response that caused this error
	Message  string         `json:"message,omitempty"`
}

RateLimitError occurs when the API rate limit is exceeded.

func (*RateLimitError) Error

func (r *RateLimitError) Error() string

func (*RateLimitError) Is

func (r *RateLimitError) Is(target error) bool

Is returns whether the provided error equals this error.

type Resource

type Resource struct {
	// Core fields
	ID          *FlexibleID      `json:"id,omitempty"`
	URI         string           `json:"uri"`
	Name        string           `json:"name"`
	Description *string          `json:"description,omitempty"`
	MimeType    *string          `json:"mimeType,omitempty"`
	Size        *int             `json:"size,omitempty"`
	IsActive    bool             `json:"isActive"`
	Metrics     *ResourceMetrics `json:"metrics,omitempty"`

	// Organizational fields
	Tags       []string `json:"tags,omitempty"`
	TeamID     *string  `json:"teamId,omitempty"`
	Team       *string  `json:"team,omitempty"`
	OwnerEmail *string  `json:"ownerEmail,omitempty"`
	Visibility *string  `json:"visibility,omitempty"`

	// Timestamps
	CreatedAt *Timestamp `json:"createdAt,omitempty"`
	UpdatedAt *Timestamp `json:"updatedAt,omitempty"`

	// Metadata fields (read-only)
	CreatedBy         *string `json:"createdBy,omitempty"`
	CreatedFromIP     *string `json:"createdFromIp,omitempty"`
	CreatedVia        *string `json:"createdVia,omitempty"`
	CreatedUserAgent  *string `json:"createdUserAgent,omitempty"`
	ModifiedBy        *string `json:"modifiedBy,omitempty"`
	ModifiedFromIP    *string `json:"modifiedFromIp,omitempty"`
	ModifiedVia       *string `json:"modifiedVia,omitempty"`
	ModifiedUserAgent *string `json:"modifiedUserAgent,omitempty"`
	ImportBatchID     *string `json:"importBatchId,omitempty"`
	FederationSource  *string `json:"federationSource,omitempty"`
	Version           *int    `json:"version,omitempty"`
}

Resource represents a ContextForge resource (read response).

type ResourceCreate

type ResourceCreate struct {
	// Required fields
	URI     string `json:"uri"`
	Name    string `json:"name"`
	Content any    `json:"content"` // Can be string or binary data

	// Optional fields (snake_case per API spec)
	Description *string  `json:"description,omitempty"`
	MimeType    *string  `json:"mime_type,omitempty"`
	Template    *string  `json:"template,omitempty"`
	Tags        []string `json:"tags,omitempty"`
}

ResourceCreate represents the request body for creating a resource. Note: Uses snake_case field names as required by the API.

type ResourceCreateOptions

type ResourceCreateOptions struct {
	TeamID     *string
	Visibility *string
}

ResourceCreateOptions specifies additional options for creating a resource. These fields are placed at the top level of the request wrapper.

type ResourceListOptions

type ResourceListOptions struct {
	ListOptions

	// IncludeInactive includes inactive resources in the results
	IncludeInactive bool `url:"include_inactive,omitempty"`

	// Tags filters resources by tags (comma-separated)
	Tags string `url:"tags,omitempty"`

	// TeamID filters resources by team ID
	TeamID string `url:"team_id,omitempty"`

	// Visibility filters resources by visibility (public, private, etc.)
	Visibility string `url:"visibility,omitempty"`
}

ResourceListOptions specifies the optional parameters to the ResourcesService.List method.

type ResourceMetrics

type ResourceMetrics struct {
	TotalExecutions      int        `json:"totalExecutions,omitempty"`
	SuccessfulExecutions int        `json:"successfulExecutions,omitempty"`
	FailedExecutions     int        `json:"failedExecutions,omitempty"`
	FailureRate          float64    `json:"failureRate,omitempty"`
	MinResponseTime      *float64   `json:"minResponseTime,omitempty"`
	MaxResponseTime      *float64   `json:"maxResponseTime,omitempty"`
	AvgResponseTime      *float64   `json:"avgResponseTime,omitempty"`
	LastExecutionTime    *Timestamp `json:"lastExecutionTime,omitempty"`
}

ResourceMetrics represents performance statistics for a resource.

type ResourceTemplate

type ResourceTemplate struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	URI         string `json:"uri"`
	MimeType    string `json:"mime_type"`
}

ResourceTemplate represents a template for creating resources.

type ResourceUpdate

type ResourceUpdate struct {
	// All fields optional (camelCase per API spec)
	URI         *string  `json:"uri,omitempty"`
	Name        *string  `json:"name,omitempty"`
	Description *string  `json:"description,omitempty"`
	MimeType    *string  `json:"mimeType,omitempty"`
	Template    *string  `json:"template,omitempty"`
	Content     any      `json:"content,omitempty"` // Can be string or binary data
	Tags        []string `json:"tags,omitempty"`
}

ResourceUpdate represents the request body for updating a resource. Note: Uses camelCase field names as required by the API.

type ResourcesService

type ResourcesService service

ResourcesService handles communication with the resource related methods of the ContextForge API.

func (*ResourcesService) Create

Create creates a new resource. The opts parameter allows setting team_id and visibility at the request wrapper level.

func (*ResourcesService) Delete

func (s *ResourcesService) Delete(ctx context.Context, resourceID string) (*Response, error)

Delete deletes a resource by its ID.

func (*ResourcesService) List

List retrieves a paginated list of resources from the ContextForge API.

func (*ResourcesService) ListTemplates

ListTemplates retrieves available resource templates.

func (*ResourcesService) Toggle

func (s *ResourcesService) Toggle(ctx context.Context, resourceID string, activate bool) (*Resource, *Response, error)

Toggle enables or disables a resource. If activate is true, the resource is enabled. If false, it is disabled.

Note: The toggle endpoint returns snake_case field names (is_active, mime_type, etc.) while other endpoints return camelCase (isActive, mimeType, etc.). This is handled internally by converting the response format.

func (*ResourcesService) Update

func (s *ResourcesService) Update(ctx context.Context, resourceID string, resource *ResourceUpdate) (*Resource, *Response, error)

Update updates an existing resource. Unlike Create, Update does not use request wrapping.

type Response

type Response struct {
	*http.Response

	// Pagination cursor extracted from response
	NextCursor string

	// Rate limiting information
	Rate Rate
}

Response wraps the standard http.Response and provides convenient access to pagination and rate limit information.

type Server

type Server struct {
	// Core fields
	ID          string         `json:"id"`
	Name        string         `json:"name"`
	Description *string        `json:"description,omitempty"`
	Icon        *string        `json:"icon,omitempty"`
	IsActive    bool           `json:"isActive,omitempty"`
	Metrics     *ServerMetrics `json:"metrics,omitempty"`

	// Association fields
	AssociatedTools     []string `json:"associatedTools,omitempty"`
	AssociatedResources []int    `json:"associatedResources,omitempty"`
	AssociatedPrompts   []int    `json:"associatedPrompts,omitempty"`
	AssociatedA2aAgents []string `json:"associatedA2aAgents,omitempty"`

	// Organizational fields
	Tags       []string `json:"tags,omitempty"`
	TeamID     *string  `json:"teamId,omitempty"`
	Team       *string  `json:"team,omitempty"`
	OwnerEmail *string  `json:"ownerEmail,omitempty"`
	Visibility *string  `json:"visibility,omitempty"`

	// Timestamps
	CreatedAt *Timestamp `json:"createdAt,omitempty"`
	UpdatedAt *Timestamp `json:"updatedAt,omitempty"`

	// Metadata fields (read-only)
	CreatedBy         *string `json:"createdBy,omitempty"`
	CreatedFromIP     *string `json:"createdFromIp,omitempty"`
	CreatedVia        *string `json:"createdVia,omitempty"`
	CreatedUserAgent  *string `json:"createdUserAgent,omitempty"`
	ModifiedBy        *string `json:"modifiedBy,omitempty"`
	ModifiedFromIP    *string `json:"modifiedFromIp,omitempty"`
	ModifiedVia       *string `json:"modifiedVia,omitempty"`
	ModifiedUserAgent *string `json:"modifiedUserAgent,omitempty"`
	ImportBatchID     *string `json:"importBatchId,omitempty"`
	FederationSource  *string `json:"federationSource,omitempty"`
	Version           *int    `json:"version,omitempty"`
}

Server represents a ContextForge server (read response).

type ServerAssociationOptions

type ServerAssociationOptions struct {
	// IncludeInactive includes inactive items in the results
	IncludeInactive bool `url:"include_inactive,omitempty"`
}

ServerAssociationOptions specifies the optional parameters for listing server associations (tools, resources, prompts).

type ServerCreate

type ServerCreate struct {
	Name        string   `json:"name"`
	Description *string  `json:"description,omitempty"`
	Icon        *string  `json:"icon,omitempty"`
	Tags        []string `json:"tags,omitempty"`

	// Association fields (snake_case per API spec)
	AssociatedTools     []string `json:"associated_tools,omitempty"`
	AssociatedResources []string `json:"associated_resources,omitempty"`
	AssociatedPrompts   []string `json:"associated_prompts,omitempty"`
	AssociatedA2aAgents []string `json:"associated_a2a_agents,omitempty"`

	// Organizational fields (snake_case per API spec)
	TeamID     *string `json:"team_id,omitempty"`
	OwnerEmail *string `json:"owner_email,omitempty"`
	Visibility *string `json:"visibility,omitempty"`
}

ServerCreate represents the request body for creating a server. Note: Uses snake_case field names as required by the API.

type ServerCreateOptions

type ServerCreateOptions struct {
	TeamID     *string
	Visibility *string
}

ServerCreateOptions specifies additional options for creating a server. These fields are placed at the top level of the request wrapper.

type ServerListOptions

type ServerListOptions struct {
	ListOptions

	// IncludeInactive includes inactive servers in the results
	IncludeInactive bool `url:"include_inactive,omitempty"`

	// Tags filters servers by tags (comma-separated)
	Tags string `url:"tags,omitempty"`

	// TeamID filters servers by team ID
	TeamID string `url:"team_id,omitempty"`

	// Visibility filters servers by visibility (public, private, etc.)
	Visibility string `url:"visibility,omitempty"`
}

ServerListOptions specifies the optional parameters to the ServersService.List method.

type ServerMetrics

type ServerMetrics struct {
	TotalExecutions      int        `json:"totalExecutions"`
	SuccessfulExecutions int        `json:"successfulExecutions"`
	FailedExecutions     int        `json:"failedExecutions"`
	FailureRate          float64    `json:"failureRate"`
	MinResponseTime      *float64   `json:"minResponseTime,omitempty"`
	MaxResponseTime      *float64   `json:"maxResponseTime,omitempty"`
	AvgResponseTime      *float64   `json:"avgResponseTime,omitempty"`
	LastExecutionTime    *Timestamp `json:"lastExecutionTime,omitempty"`
}

ServerMetrics represents performance statistics for a server.

type ServerUpdate

type ServerUpdate struct {
	Name        *string  `json:"name,omitempty"`
	Description *string  `json:"description,omitempty"`
	Icon        *string  `json:"icon,omitempty"`
	Tags        []string `json:"tags,omitempty"`

	// Association fields (camelCase per API spec)
	AssociatedTools     []string `json:"associatedTools,omitempty"`
	AssociatedResources []string `json:"associatedResources,omitempty"`
	AssociatedPrompts   []string `json:"associatedPrompts,omitempty"`
	AssociatedA2aAgents []string `json:"associatedA2aAgents,omitempty"`

	// Organizational fields (camelCase per API spec)
	TeamID     *string `json:"teamId,omitempty"`
	OwnerEmail *string `json:"ownerEmail,omitempty"`
	Visibility *string `json:"visibility,omitempty"`
}

ServerUpdate represents the request body for updating a server. Note: Uses camelCase field names as required by the API.

type ServersService

type ServersService service

ServersService handles communication with the server related methods of the ContextForge API.

func (*ServersService) Create

func (s *ServersService) Create(ctx context.Context, server *ServerCreate, opts *ServerCreateOptions) (*Server, *Response, error)

Create creates a new server. The opts parameter allows setting team_id and visibility at the request wrapper level.

func (*ServersService) Delete

func (s *ServersService) Delete(ctx context.Context, serverID string) (*Response, error)

Delete deletes a server by its ID.

func (*ServersService) Get

func (s *ServersService) Get(ctx context.Context, serverID string) (*Server, *Response, error)

Get retrieves a specific server by its ID.

func (*ServersService) List

func (s *ServersService) List(ctx context.Context, opts *ServerListOptions) ([]*Server, *Response, error)

List retrieves a paginated list of servers from the ContextForge API.

func (*ServersService) ListPrompts

func (s *ServersService) ListPrompts(ctx context.Context, serverID string, opts *ServerAssociationOptions) ([]*Prompt, *Response, error)

ListPrompts retrieves all prompts associated with a specific server.

func (*ServersService) ListResources

func (s *ServersService) ListResources(ctx context.Context, serverID string, opts *ServerAssociationOptions) ([]*Resource, *Response, error)

ListResources retrieves all resources associated with a specific server.

func (*ServersService) ListTools

func (s *ServersService) ListTools(ctx context.Context, serverID string, opts *ServerAssociationOptions) ([]*Tool, *Response, error)

ListTools retrieves all tools associated with a specific server.

func (*ServersService) Toggle

func (s *ServersService) Toggle(ctx context.Context, serverID string, activate bool) (*Server, *Response, error)

Toggle toggles a server's active status.

func (*ServersService) Update

func (s *ServersService) Update(ctx context.Context, serverID string, server *ServerUpdate) (*Server, *Response, error)

Update updates an existing server. Note: The API does not wrap the request body for server updates.

type Timestamp

type Timestamp struct {
	time.Time
}

Timestamp represents a time that can be unmarshalled from the ContextForge API. The API returns timestamps without timezone information, so we need custom parsing.

func (Timestamp) MarshalJSON

func (t Timestamp) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for Timestamp.

func (*Timestamp) UnmarshalJSON

func (t *Timestamp) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for Timestamp.

type Tool

type Tool struct {
	ID          string         `json:"id,omitempty"`
	Name        string         `json:"name"`
	Description *string        `json:"description,omitempty"`
	InputSchema map[string]any `json:"inputSchema,omitempty"`
	Enabled     bool           `json:"enabled,omitempty"`
	TeamID      *string        `json:"teamId,omitempty"`
	Visibility  string         `json:"visibility,omitempty"`
	Tags        []string       `json:"tags,omitempty"`
	CreatedAt   *Timestamp     `json:"createdAt,omitempty"`
	UpdatedAt   *Timestamp     `json:"updatedAt,omitempty"`
}

Tool represents a ContextForge tool.

type ToolCreateOptions

type ToolCreateOptions struct {
	TeamID     *string
	Visibility *string
}

ToolCreateOptions specifies additional options for creating a tool. These fields are placed at the top level of the request wrapper.

type ToolListOptions

type ToolListOptions struct {
	ListOptions

	// IncludeInactive includes inactive tools in the results
	IncludeInactive bool `url:"include_inactive,omitempty"`

	// Tags filters tools by tags (comma-separated)
	Tags string `url:"tags,omitempty"`

	// TeamID filters tools by team ID
	TeamID string `url:"team_id,omitempty"`

	// Visibility filters tools by visibility (public, private, etc.)
	Visibility string `url:"visibility,omitempty"`
}

ToolListOptions specifies the optional parameters to the ToolsService.List method.

type ToolsService

type ToolsService service

ToolsService handles communication with the tool related methods of the ContextForge API.

func (*ToolsService) Create

func (s *ToolsService) Create(ctx context.Context, tool *Tool, opts *ToolCreateOptions) (*Tool, *Response, error)

Create creates a new tool. The opts parameter allows setting team_id and visibility at the request wrapper level.

func (*ToolsService) Delete

func (s *ToolsService) Delete(ctx context.Context, toolID string) (*Response, error)

Delete deletes a tool by its ID.

func (*ToolsService) Get

func (s *ToolsService) Get(ctx context.Context, toolID string) (*Tool, *Response, error)

Get retrieves a specific tool by its ID.

func (*ToolsService) List

func (s *ToolsService) List(ctx context.Context, opts *ToolListOptions) ([]*Tool, *Response, error)

List retrieves a paginated list of tools from the ContextForge API.

func (*ToolsService) Toggle

func (s *ToolsService) Toggle(ctx context.Context, toolID string, activate bool) (*Tool, *Response, error)

Toggle toggles a tool's active status.

func (*ToolsService) Update

func (s *ToolsService) Update(ctx context.Context, toolID string, tool *Tool) (*Tool, *Response, error)

Update updates an existing tool.

Jump to

Keyboard shortcuts

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