1package transport
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "sync"
8
9 "github.com/mark3labs/mcp-go/mcp"
10 "github.com/mark3labs/mcp-go/server"
11)
12
13type InProcessTransport struct {
14 server *server.MCPServer
15
16 onNotification func(mcp.JSONRPCNotification)
17 notifyMu sync.RWMutex
18}
19
20func NewInProcessTransport(server *server.MCPServer) *InProcessTransport {
21 return &InProcessTransport{
22 server: server,
23 }
24}
25
26func (c *InProcessTransport) Start(ctx context.Context) error {
27 return nil
28}
29
30func (c *InProcessTransport) SendRequest(ctx context.Context, request JSONRPCRequest) (*JSONRPCResponse, error) {
31 requestBytes, err := json.Marshal(request)
32 if err != nil {
33 return nil, fmt.Errorf("failed to marshal request: %w", err)
34 }
35 requestBytes = append(requestBytes, '\n')
36
37 respMessage := c.server.HandleMessage(ctx, requestBytes)
38 respByte, err := json.Marshal(respMessage)
39 if err != nil {
40 return nil, fmt.Errorf("failed to marshal response message: %w", err)
41 }
42 rpcResp := JSONRPCResponse{}
43 err = json.Unmarshal(respByte, &rpcResp)
44 if err != nil {
45 return nil, fmt.Errorf("failed to unmarshal response message: %w", err)
46 }
47
48 return &rpcResp, nil
49}
50
51func (c *InProcessTransport) SendNotification(ctx context.Context, notification mcp.JSONRPCNotification) error {
52 notificationBytes, err := json.Marshal(notification)
53 if err != nil {
54 return fmt.Errorf("failed to marshal notification: %w", err)
55 }
56 notificationBytes = append(notificationBytes, '\n')
57 c.server.HandleMessage(ctx, notificationBytes)
58
59 return nil
60}
61
62func (c *InProcessTransport) SetNotificationHandler(handler func(notification mcp.JSONRPCNotification)) {
63 c.notifyMu.Lock()
64 defer c.notifyMu.Unlock()
65 c.onNotification = handler
66}
67
68func (*InProcessTransport) Close() error {
69 return nil
70}
71
72func (c *InProcessTransport) GetSessionId() string {
73 return ""
74}