mcp

package
v0.0.15-test Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2025 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MethodInitialize = "initialize"
	MethodPing       = "ping"
	ProtocolVersion  = "2024-11-05"
)
View Source
const (
	// Client => Server
	MethodPromptsList = "prompts/list"
	MethodPromptsGet  = "prompts/get"
)
View Source
const (
	// Client => Server
	MethodResourcesList         = "resources/list"
	MethodResourcesTemplateList = "resources/templates/list"
	MethodResourcesRead         = "resources/read"
	MethodResourcesSubscribe    = "resources/subscribe"
	MethodResourcesUnsubscribe  = "resources/unsubscribe"

	// Server => Client
	NotificationResourcesListChanged = "notifications/resources/list_changed"
	NofiticationResourcesUpdated     = "notifications/resources/updated"
)
View Source
const (
	SSEPingIntervalS  = 30
	SSEMessageChanCap = 100
	SSEContentType    = "text/event-stream; charset=utf-8"
)
View Source
const (
	// Client => Server
	MethodToolsList = "tools/list"
	MethodToolsCall = "tools/call"
)
View Source
const (
	JsonRPCVersion = "2.0"
)
View Source
const (
	ProcessChanCap = 1000
)

Variables

View Source
var (
	ErrParseError     = &Error{Code: -32700, Message: "Parse error"}
	ErrInvalidRequest = &Error{Code: -32600, Message: "Invalid Request"}
	ErrMethodNotFound = &Error{Code: -32601, Message: "Method not found"}
	ErrInvalidParams  = &Error{Code: -32602, Message: "Invalid params"}
	ErrInternalError  = &Error{Code: -32603, Message: "Internal error"}

	ErrInvalidSessionID = &Error{Code: 400, Message: "Invalid session ID"}
	ErrSessionNotFound  = &Error{Code: 404, Message: "Could not find session"}
	ErrTooManyRequests  = &Error{Code: 429, Message: "Too many requests"}
)
View Source
var DefaultCapabilities = M{
	"experimental": M{},
	"prompts":      M{"listChanged": false},
	"resources":    M{"subscribe": false, "listChanged": false},
	"tools":        M{"listChanged": false},
}

Functions

This section is empty.

Types

type ClientInfo

type ClientInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

type Content

type Content struct {
	Type string `json:"type"`
	Text string `json:"text"`
}

type Error

type Error struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

Error

func (*Error) Error

func (e *Error) Error() string

func (*Error) JsonRPC

func (e *Error) JsonRPC() Response

type InitializeRequest

type InitializeRequest struct {
	ProtocolVersion string      `json:"protocolVersion"`
	Capabilities    M           `json:"capabilities"`
	ClientInfo      *ClientInfo `json:"clientInfo"`
}
{
	"method": "initialize",
	"params": {
	  "protocolVersion": "2024-11-05",
	  "capabilities": {
		"sampling": {},
		"roots": {
		  "listChanged": true
		}
	  },
	  "clientInfo": {
		"name": "mcp-inspector",
		"version": "0.0.1"
	  }
	},
	"jsonrpc": "2.0",
	"id": 0
  }

type InitializeResponse

type InitializeResponse struct {
	ProtocolVersion string     `json:"protocolVersion"`
	Capabilities    M          `json:"capabilities"`
	ServerInfo      ServerInfo `json:"serverInfo"`
}
{
	"jsonrpc": "2.0",
	"id": 0,
	"result": {
	  "protocolVersion": "2024-11-05",
	  "capabilities": {
		"experimental": {},
		"prompts": {
		  "listChanged": false
		},
		"resources": {
		  "subscribe": false,
		  "listChanged": false
		},
		"tools": {
		  "listChanged": false
		}
	  },
	  "serverInfo": {
		"name": "weather",
		"version": "1.4.1"
	  }
	}
  }

type M

type M map[string]interface{}

type MCP

type MCP struct {
	ProcessChan chan ProcessCtx
	// contains filtered or unexported fields
}

func NewMCP

func NewMCP() *MCP

func (*MCP) Close

func (m *MCP) Close()

func (*MCP) GetSession

func (m *MCP) GetSession(id string) *Session

func (*MCP) HandleMessages

func (m *MCP) HandleMessages(c *gin.Context)

func (*MCP) HandleSSE

func (m *MCP) HandleSSE(c *gin.Context)

type Notification

type Notification struct {
	JsonRPC string      `json:"jsonrpc"`
	Method  string      `json:"method"`
	Params  interface{} `json:"params,omitempty"`
}

Notifications

{
	jsonrpc: "2.0",
	method: string,
	params?: object
}

type ProcessCtx

type ProcessCtx struct {
	Session *Session
	Request *Request
}

type Prompt

type Prompt struct {
	Name        string           `json:"name"`
	Description string           `json:"description,omitempty"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
}

Prompt

{
	name: string;              // Unique identifier for the prompt
	description?: string;      // Human-readable description
	arguments?: [              // Optional list of arguments
		{
			name: string;          // Argument identifier
			description?: string;  // Argument description
			required?: boolean;    // Whether argument is required
		}
	]
}

type PromptArgument

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

type PromptContent

type PromptContent struct {
	Type     string      `json:"type"`
	Text     string      `json:"text,omitempty"`
	Resource interface{} `json:"resource,omitempty"` // Resource or ResourceTemplate
}

type PromptMessage

type PromptMessage struct {
	Role    string        `json:"role"`
	Content PromptContent `json:"content"`
}

type PromptsGetRequest

type PromptsGetRequest struct {
	Name      string `json:"name"`
	Arguments M      `json:"arguments"`
}

Use Prompt Request

{
	method: "prompts/get",
	params: {
		name: "analyze-code",
		arguments: {
			language: "python"
		}
	}
}

Response

{
	description: "Analyze Python code for potential improvements",
	messages: [
		{
			role: "user",
			content: {
				type: "text",
				text: "Please analyze the following Python code for potential improvements:\n\n```python\ndef calculate_sum(numbers):\n    total = 0\n    for num in numbers:\n        total = total + num\n    return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result)\n```"
			}
		}
	]
}

type PromptsGetResponse

type PromptsGetResponse struct {
	Description string          `json:"description"`
	Messages    []PromptMessage `json:"messages"`
}

type PromptsListResponse

type PromptsListResponse struct {
	Prompts []Prompt `json:"prompts"`
}

ListPrompts

{
	prompts: [
		{
			name: "analyze-code",
			description: "Analyze code for potential improvements",
			arguments: [
				{
					name: "language",
					description: "Programming language",
					required: true
				}
			]
		}
	]
}

type ReadingResource

type ReadingResource struct {
	Contents []ReadingResourceContent `json:"contents"`
}
			// One of:
			text?: string;      // For text resources
			blob?: string;      // For binary resources (base64 encoded)
		}
	]
}

type ReadingResourceContent

type ReadingResourceContent struct {
	URI      string `json:"uri"`
	MimeType string `json:"mimeType,omitempty"`
	Text     string `json:"text,omitempty"`
	Blob     string `json:"blob,omitempty"`
}

type Request

type Request struct {
	JsonRPC string      `json:"jsonrpc"`
	ID      interface{} `json:"id"`
	Method  string      `json:"method"`
	Params  interface{} `json:"params,omitempty"`
}

Request

{
	jsonrpc: "2.0",
	id: number | string,
	method: string,
	params?: object
}

type Resource

type Resource struct {
	URI         string `json:"uri"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	MimeType    string `json:"mimeType,omitempty"`
}

Direct resources

{
	uri: string;           // Unique identifier for the resource
	name: string;          // Human-readable name
	description?: string;  // Optional description
	mimeType?: string;     // Optional MIME type
}

type ResourceTemplate

type ResourceTemplate struct {
	URITemplate string `json:"uriTemplate"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	MimeType    string `json:"mimeType,omitempty"`
}

Resource templates

{
	uriTemplate: string;   // URI template following RFC 6570
	name: string;          // Human-readable name for this type
	description?: string;  // Optional description
	mimeType?: string;     // Optional MIME type for all matching resources
}

type ResourcesReadRequest

type ResourcesReadRequest struct {
	URI string `json:"uri"`
}

type Response

type Response struct {
	JsonRPC string      `json:"jsonrpc"`
	ID      interface{} `json:"id"`
	Result  interface{} `json:"result,omitempty"`
	Error   *Error      `json:"error,omitempty"`
}

Response

{
	jsonrpc: "2.0",
	id: number | string,
	result?: object,
	error?: {
		code: number,
		message: string,
		data?: unknown
	}
}

func NewErrorResponse

func NewErrorResponse(id interface{}, code int, err error) *Response

func NewResponse

func NewResponse(id interface{}, result interface{}) *Response

type SSESession

type SSESession struct {
	SessionID string
	Events    map[string]chan string
	Stop      chan bool
	// contains filtered or unexported fields
}

SSE Session 维持一个 SSE 连接的会话 会话中包含了 SSE 连接的 ID,事件通道,停止通道 事件通道用于发送事件,停止通道用于停止会话 需要轮询发送 ping 事件以保持连接

func NewSSESession

func NewSSESession(c *gin.Context) *SSESession

func (*SSESession) Close

func (s *SSESession) Close()

func (*SSESession) SendEvent

func (s *SSESession) SendEvent(event string, data string)

type SSEWriter

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

func NewSSEWriter

func NewSSEWriter(c *gin.Context, id string) *SSEWriter

func (*SSEWriter) Write

func (w *SSEWriter) Write(p []byte) (n int, err error)

func (*SSEWriter) WriteEndpoing

func (w *SSEWriter) WriteEndpoing()

WriteEndpoing event: endpoint data: /message?sessionId=285d67ee-1c17-40d9-ab03-173d5ff48419

func (*SSEWriter) WriteEvent

func (w *SSEWriter) WriteEvent(event string, data string)

func (*SSEWriter) WriteMessage

func (w *SSEWriter) WriteMessage(data string)

type ServerInfo

type ServerInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

type Session

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

func NewSession

func NewSession(c *gin.Context, id string) *Session

func (*Session) SaveClientInfo

func (s *Session) SaveClientInfo(c *ClientInfo)

func (*Session) Write

func (s *Session) Write(p []byte) (n int, err error)

func (*Session) WriteError

func (s *Session) WriteError(req *Request, err error)

func (*Session) WriteResponse

func (s *Session) WriteResponse(req *Request, data interface{}) error

type Tool

type Tool struct {
	Name        string     `json:"name"`
	Description string     `json:"description,omitempty"`
	InputSchema ToolSchema `json:"inputSchema"`
}

Tool

{
	name: string;          // Unique identifier for the tool
	description?: string;  // Human-readable description
	inputSchema: {         // JSON Schema for the tool's parameters
		type: "object",
		properties: { ... }  // Tool-specific parameters
	}
}

{
	name: "analyze_csv",
	description: "Analyze a CSV file",
	inputSchema: {
		type: "object",
		properties: {
			filepath: { type: "string" },
			operations: {
				type: "array",
				items: {
					enum: ["sum", "average", "count"]
				}
			}
		}
	}
}

{
	"jsonrpc": "2.0",
	"id": 1,
	"result": {
	  "tools": [
		{
		  "name": "get_alerts",
		  "description": "Get weather alerts for a US state.\n\n    Args:\n        state: Two-letter US state code (e.g. CA, NY)\n    ",
		  "inputSchema": {
			"properties": {
			  "state": {
				"title": "State",
				"type": "string"
			  }
			},
			"required": [
			  "state"
			],
			"title": "get_alertsArguments",
			"type": "object"
		  }
		},
		{
		  "name": "get_forecast",
		  "description": "Get weather forecast for a location.\n\n    Args:\n        latitude: Latitude of the location\n        longitude: Longitude of the location\n    ",
		  "inputSchema": {
			"properties": {
			  "latitude": {
				"title": "Latitude",
				"type": "number"
			  },
			  "longitude": {
				"title": "Longitude",
				"type": "number"
			  }
			},
			"required": [
			  "latitude",
			  "longitude"
			],
			"title": "get_forecastArguments",
			"type": "object"
		  }
		}
	  ]
	}
  }

type ToolSchema

type ToolSchema struct {
	Type       string   `json:"type"`
	Properties M        `json:"properties"`
	Required   []string `json:"required,omitempty"`
}

type ToolsCallRequest

type ToolsCallRequest struct {
	Name      string `json:"name"`
	Arguments M      `json:"arguments"`
}
{
	"method": "tools/call",
	"params": {
	  "name": "chatlog",
	  "arguments": {
		"start": "2006-11-12",
		"end": "2020-11-20",
		"limit": "50",
		"offset": "6"
	  },
	  "_meta": {
		"progressToken": 1
	  }
	},
	"jsonrpc": "2.0",
	"id": 3
  }

type ToolsCallResponse

type ToolsCallResponse struct {
	Content []Content `json:"content"`
	IsError bool      `json:"isError"`
}
{
	"jsonrpc": "2.0",
	"id": 2,
	"result": {
	  "content": [
		{
		  "type": "text",
		  "text": "\nEvent: Winter Storm Warning\n"
		}
	  ],
	  "isError": false
	}
  }

Jump to

Keyboard shortcuts

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