summaryrefslogtreecommitdiff
path: root/internal/mcp/server.go
blob: 645c0cf7a113c40250d29c1bf56db211fa3a169c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// Package mcp provides the MCP server core — struct definition, constructor, main loop, and message dispatch.
package mcp

import (
	"bufio"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"sync"

	"codeberg.org/snonux/hexai/internal"
	"codeberg.org/snonux/hexai/internal/promptstore"
)

// SlashCommandSyncer is the minimal sync contract the MCP server depends on.
type SlashCommandSyncer interface {
	SyncCreate(prompt *promptstore.Prompt) error
	SyncUpdate(prompt *promptstore.Prompt) error
	Delete(promptName string) error
}

// Server implements an MCP server over stdio using JSON-RPC 2.0.
// Follows the same pattern as the LSP server with dispatch table and thread safety.
type Server struct {
	in          *bufio.Reader
	out         io.Writer
	outMu       sync.Mutex
	logger      *log.Logger
	store       promptstore.PromptStore
	syncer      SlashCommandSyncer
	initialized bool
	mu          sync.RWMutex

	// Dispatch table for JSON-RPC methods
	handlers map[string]func(Request)
}

// NewServer creates a new MCP server with the given store and I/O streams.
// The store provides access to prompts; logger is used for debugging.
func NewServer(r io.Reader, w io.Writer, logger *log.Logger, store promptstore.PromptStore, syncer SlashCommandSyncer) *Server {
	s := &Server{
		in:     bufio.NewReader(r),
		out:    w,
		logger: logger,
		store:  store,
		syncer: syncer,
	}

	// Initialize dispatch table mapping JSON-RPC methods to handler functions
	s.handlers = map[string]func(Request){
		"initialize":                s.handleInitialize,
		"initialized":               s.handleInitialized,
		"prompts/list":              s.handlePromptsList,
		"prompts/get":               s.handlePromptsGet,
		"prompts/create":            s.handlePromptsCreate,
		"prompts/update":            s.handlePromptsUpdate,
		"prompts/delete":            s.handlePromptsDelete,
		"tools/list":                s.handleToolsList,
		"tools/call":                s.handleToolsCall,
		"notifications/initialized": s.handleInitialized,
	}

	return s
}

// Run starts the server main loop, reading and dispatching requests.
// Returns on EOF or fatal error.
func (s *Server) Run() error {
	for {
		body, err := s.readMessage()
		if errors.Is(err, io.EOF) {
			return nil
		}
		if err != nil {
			return fmt.Errorf("read message: %w", err)
		}

		var req Request
		if err := json.Unmarshal(body, &req); err != nil {
			s.logger.Printf("invalid JSON: %v", err)
			s.sendError(nil, ErrCodeParseError, "Parse error")
			continue
		}

		if req.Method == "" {
			// Response from client; ignore
			continue
		}

		// Dispatch request
		go s.handle(req)
	}
}

// handle dispatches a request to the appropriate handler.
func (s *Server) handle(req Request) {
	handler, ok := s.handlers[req.Method]
	if !ok {
		s.logger.Printf("method not found: %s", req.Method)
		s.sendError(req.ID, ErrCodeMethodNotFound, fmt.Sprintf("Method not found: %s", req.Method))
		return
	}

	handler(req)
}

// handleInitialize processes the initialize request and returns server capabilities.
func (s *Server) handleInitialize(req Request) {
	var params InitializeRequest
	if err := json.Unmarshal(req.Params, &params); err != nil {
		s.sendError(req.ID, ErrCodeInvalidParams, "Invalid initialize params")
		return
	}

	s.logger.Printf("initialize from client: %s %s (protocol: %s)",
		params.ClientInfo.Name, params.ClientInfo.Version, params.ProtocolVersion)

	// Negotiate protocol version: echo client's version if valid, otherwise use latest.
	// This follows the MCP spec where the server responds with a version it supports.
	negotiatedVersion := negotiateProtocolVersion(params.ProtocolVersion)
	s.logger.Printf("negotiated protocol version: %s", negotiatedVersion)

	result := InitializeResult{
		ProtocolVersion: negotiatedVersion,
		Capabilities: ServerCapabilities{
			Prompts: &PromptsCapability{
				ListChanged: true, // Server sends notifications when prompt list changes
				Mutable:     true, // Advertise that we support create/update/delete
			},
			Tools: &ToolsCapability{
				ListChanged: false, // Tool list is static (no dynamic changes)
			},
		},
		ServerInfo: ServerInfo{
			Name:    "hexai-mcp-server",
			Version: internal.Version,
		},
	}

	s.mu.Lock()
	s.initialized = true
	s.mu.Unlock()

	s.sendResponse(req.ID, result)
}

// negotiateProtocolVersion returns the client's version if supported,
// otherwise returns the latest version this server supports.
func negotiateProtocolVersion(clientVersion string) string {
	for _, v := range ValidProtocolVersions {
		if v == clientVersion {
			return clientVersion
		}
	}
	return LatestProtocolVersion
}

// handleInitialized processes the initialized notification.
// This is sent by the client after receiving initialize response.
func (s *Server) handleInitialized(_ Request) {
	s.logger.Printf("client sent initialized notification")
	// No response required for notifications
}

// sendResponse sends a successful JSON-RPC response.
func (s *Server) sendResponse(id any, result any) {
	resp := Response{
		JSONRPC: "2.0",
		ID:      id,
		Result:  result,
	}
	if err := s.writeMessage(resp); err != nil {
		s.logger.Printf("write response error: %v", err)
	}
}

// sendError sends an error JSON-RPC response.
func (s *Server) sendError(id any, code int, message string) {
	resp := Response{
		JSONRPC: "2.0",
		ID:      id,
		Error: &RespError{
			Code:    code,
			Message: message,
		},
	}
	if err := s.writeMessage(resp); err != nil {
		s.logger.Printf("write error response error: %v", err)
	}
}

// sendToolSuccess sends a successful tool result.
func (s *Server) sendToolSuccess(id any, message string) {
	result := CallToolResult{
		Content: []ToolContent{{Type: "text", Text: message}},
		IsError: false,
	}
	s.sendResponse(id, result)
}

// sendToolError sends a tool error result (business logic error, not protocol error).
func (s *Server) sendToolError(id any, message string) {
	result := CallToolResult{
		Content: []ToolContent{{Type: "text", Text: message}},
		IsError: true,
	}
	s.sendResponse(id, result)
}

// sendPromptsListChangedNotification notifies the client that the prompt list has changed.
// This allows clients to refresh their cached prompt lists.
func (s *Server) sendPromptsListChangedNotification() {
	notification := map[string]interface{}{
		"jsonrpc": "2.0",
		"method":  "notifications/prompts/list_changed",
	}

	if err := s.writeMessage(notification); err != nil {
		s.logger.Printf("failed to send prompts/list_changed notification: %v", err)
	}
}