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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
package main

import (
	"bufio"
	"context"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"sync"
	"time"

	"path/filepath"
	"strings"

	varlinklib "codeberg.org/Profpatsch/Profpatsch/users/Profpatsch/varlink-lib"
	"github.com/varlink/go/varlink/idl"
)

var (
	varlinkAddress = flag.String("varlink-address", "", "Varlink service address (e.g., unix:/run/user/1000/service.sock)")
	interfaceName  = flag.String("interface", "", "Varlink interface name (e.g., de.profpatsch.ClaudeLastPosition)")
	debugLog       = flag.Bool("debug", false, "Enable debug logging to stderr")
	httpMode       = flag.Bool("http-mode", false, "Run as HTTP server instead of stdio")
	httpPort       = flag.Int("http-port", 3000, "HTTP port to listen on (only with --http-mode)")
)

type Bridge struct {
	varlinkClient *varlinklib.VarlinkClient
	tools         []Tool
	lastID        int64
	cache         *Cache
	cacheDir      string     // Base cache directory
	sessionDir    string     // Directory for this session's files
	sessionID     string     // MCP session ID for HTTP mode
	expiresAt     int64      // Session expiration timestamp
	sessionMu     sync.Mutex // Protects lastID and session state in HTTP mode
}

func main() {
	flag.Parse()

	if *varlinkAddress == "" || *interfaceName == "" {
		fmt.Fprintf(os.Stderr, "Usage: %s --varlink-address=<address> --interface=<name>\n", os.Args[0])
		fmt.Fprintf(os.Stderr, "Example: %s --varlink-address=unix:/run/user/1000/service.sock --interface=de.profpatsch.Service\n", os.Args[0])
		os.Exit(1)
	}

	// Setup logging to stderr
	if !*debugLog {
		log.SetOutput(os.Stderr)
		log.SetFlags(0)
		log.SetPrefix("")
	} else {
		log.SetOutput(os.Stderr)
		log.SetFlags(log.Ltime | log.Lshortfile)
	}

	ctx := context.Background()

	// Connect to varlink service and introspect
	log.Printf("Connecting to varlink service at %s...\n", *varlinkAddress)
	varlinkClient, err := varlinklib.NewVarlinkClient(ctx, *varlinkAddress, *interfaceName)
	if err != nil {
		log.Fatalf("Failed to initialize varlink client: %v\n", err)
	}
	defer varlinkClient.Close()

	log.Printf("Successfully connected and introspected interface %s\n", *interfaceName)

	// Build MCP tools from varlink interface
	tools, err := buildTools(varlinkClient.GetIDL(), *interfaceName)
	if err != nil {
		log.Fatalf("Failed to build MCP tools: %v\n", err)
	}

	log.Printf("Discovered %d methods as MCP tools\n", len(tools))
	if *debugLog {
		for _, tool := range tools {
			log.Printf("  - %s\n", tool.Name)
		}
	}

	// Initialize cache (use XDG_CACHE_HOME or default to ~/.cache)
	xdgCache := os.Getenv("XDG_CACHE_HOME")
	if xdgCache == "" {
		xdgCache = filepath.Join(os.Getenv("HOME"), ".cache")
	}
	cacheDir := filepath.Join(xdgCache, "varlink-mcp-bridge")
	cache, err := InitCache(cacheDir)
	if err != nil {
		log.Fatalf("Failed to initialize cache: %v\n", err)
	}
	defer cache.Close()

	// In HTTP mode, session directory will be created per-session
	// In stdio mode, create a one-time session directory
	var sessionDir string
	if !*httpMode {
		// Create session directory in ~/.cache/varlink-mcp-bridge/sessions/<session-id>/
		sessionID := generateSessionID()
		sessionDir = filepath.Join(cacheDir, "sessions", sessionID)
		if err := os.MkdirAll(sessionDir, 0755); err != nil {
			log.Fatalf("Failed to create session directory: %v\n", err)
		}
		log.Printf("Session directory: %s\n", sessionDir)
	}

	bridge := &Bridge{
		varlinkClient: varlinkClient,
		tools:         tools,
		lastID:        -1,
		cache:         cache,
		cacheDir:      cacheDir,
		sessionDir:    sessionDir,
	}

	// Start in appropriate mode
	if *httpMode {
		log.Printf("Starting MCP bridge (HTTP mode on port %d)...\n", *httpPort)
		bridge.runHTTP(ctx)
	} else {
		log.Println("Starting MCP bridge (stdio mode)...")
		bridge.runStdio(ctx)
	}
}

func (b *Bridge) runStdio(ctx context.Context) {
	scanner := bufio.NewScanner(os.Stdin)
	encoder := json.NewEncoder(os.Stdout)

	for scanner.Scan() {
		line := scanner.Bytes()
		if *debugLog {
			log.Printf("Received: %s\n", string(line))
		}

		// Parse request
		var req JSONRPCRequest
		if err := json.Unmarshal(line, &req); err != nil {
			b.sendError(encoder, 0, ErrCodeParseError, "Parse error", err.Error())
			continue
		}

		// Validate JSON-RPC version
		if req.JSONRPC != "2.0" {
			if req.ID != nil {
				b.sendError(encoder, *req.ID, ErrCodeInvalidRequest, "Invalid request", "jsonrpc must be '2.0'")
			}
			continue
		}

		// Validate monotonic ID (only for requests, not notifications)
		if req.ID != nil {
			if *req.ID <= b.lastID {
				b.sendError(encoder, *req.ID, ErrCodeInvalidRequest, "Invalid request", "ID must be monotonically increasing")
				continue
			}
			b.lastID = *req.ID
		}

		// Handle request
		resp := b.handleRequest(ctx, req)

		// Only send response for requests, not notifications
		if req.ID != nil {
			// Send response
			if err := encoder.Encode(resp); err != nil {
				log.Printf("Failed to encode response: %v\n", err)
				return
			}

			if *debugLog {
				respBytes, _ := json.Marshal(resp)
				log.Printf("Sent: %s\n", string(respBytes))
			}
		} else if *debugLog {
			log.Printf("Notification handled: %s\n", req.Method)
		}
	}

	if err := scanner.Err(); err != nil {
		log.Printf("Scanner error: %v\n", err)
	}
}

func (b *Bridge) runHTTP(ctx context.Context) {
	http.HandleFunc("/mcp", func(w http.ResponseWriter, r *http.Request) {
		b.handleMCPEndpoint(ctx, w, r)
	})

	addr := fmt.Sprintf("127.0.0.1:%d", *httpPort)
	log.Printf("Listening on http://%s/mcp\n", addr)

	if err := http.ListenAndServe(addr, nil); err != nil {
		log.Fatalf("HTTP server error: %v\n", err)
	}
}

func (b *Bridge) handleMCPEndpoint(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	// Security: Validate Origin header to prevent DNS rebinding attacks
	origin := r.Header.Get("Origin")
	if origin != "" && !isAllowedOrigin(origin) {
		http.Error(w, "Forbidden origin", http.StatusForbidden)
		log.Printf("Rejected request from origin: %s\n", origin)
		return
	}

	switch r.Method {
	case http.MethodPost:
		b.handleMCPPost(ctx, w, r)
	case http.MethodGet:
		b.handleMCPGet(ctx, w, r)
	case http.MethodDelete:
		b.handleMCPDelete(ctx, w, r)
	default:
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
	}
}

func (b *Bridge) handleMCPPost(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	// Read request body
	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Failed to read request body", http.StatusBadRequest)
		return
	}
	defer r.Body.Close()

	if *debugLog {
		log.Printf("POST /mcp: %s\n", string(body))
	}

	// Parse JSON-RPC request
	var req JSONRPCRequest
	if err := json.Unmarshal(body, &req); err != nil {
		http.Error(w, "Invalid JSON-RPC request", http.StatusBadRequest)
		return
	}

	// Load existing session if header present
	existingSessionID := r.Header.Get("Mcp-Session-Id")
	if existingSessionID != "" && req.Method != "initialize" {
		b.sessionMu.Lock()
		session, err := b.cache.LoadSession(existingSessionID)
		if err != nil {
			b.sessionMu.Unlock()
			log.Printf("Error loading session %s: %v\n", existingSessionID, err)
			http.Error(w, "Failed to load session", http.StatusInternalServerError)
			return
		}
		if session == nil {
			b.sessionMu.Unlock()
			// Session expired or not found
			http.Error(w, "Session not found or expired", http.StatusNotFound)
			return
		}
		// Restore session state
		b.sessionID = session.SessionID
		b.lastID = session.LastID
		b.sessionDir = session.SessionDir
		b.expiresAt = session.ExpiresAt
		b.sessionMu.Unlock()
	}

	// Validate monotonic ID (only for requests, not notifications)
	// Notifications have ID == nil
	if req.ID != nil {
		b.sessionMu.Lock()
		if *req.ID <= b.lastID {
			b.sessionMu.Unlock()
			errorResp := b.makeErrorResponse(*req.ID, ErrCodeInvalidRequest, "Invalid request", "ID must be monotonically increasing")
			b.sendJSONResponse(w, r, errorResp)
			return
		}
		b.lastID = *req.ID
		b.sessionMu.Unlock()
	}

	// Handle request
	resp := b.handleRequest(ctx, req)

	// For initialize request, create new session
	if req.Method == "initialize" && resp.Error == nil {
		b.sessionMu.Lock()
		if b.sessionID == "" {
			b.sessionID = generateSessionID()
			b.expiresAt = time.Now().Add(2 * time.Hour).Unix() // 2 hour expiration
			b.sessionDir = filepath.Join(b.cacheDir, "sessions", b.sessionID)

			// Create session directory
			if err := os.MkdirAll(b.sessionDir, 0755); err != nil {
				b.sessionMu.Unlock()
				log.Printf("Failed to create session directory: %v\n", err)
				http.Error(w, "Failed to create session", http.StatusInternalServerError)
				return
			}

			w.Header().Set("Mcp-Session-Id", b.sessionID)
			log.Printf("Created new session: %s (expires: %s)\n", b.sessionID, time.Unix(b.expiresAt, 0).Format(time.RFC3339))
		}
		b.sessionMu.Unlock()
	}

	// Save session state after processing request (if we have a session and it's not a notification)
	if b.sessionID != "" && req.ID != nil {
		b.sessionMu.Lock()
		if err := b.cache.SaveSession(b.sessionID, b.lastID, b.sessionDir, b.expiresAt); err != nil {
			log.Printf("Warning: failed to save session state: %v\n", err)
		}
		b.sessionMu.Unlock()
	}

	// Notifications (ID == nil) don't get a response
	if req.ID == nil {
		w.WriteHeader(http.StatusAccepted)
		if *debugLog {
			log.Printf("Notification handled: %s\n", req.Method)
		}
		return
	}

	// Send JSON response for requests
	b.sendJSONResponse(w, r, resp)
}

func (b *Bridge) handleMCPGet(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	// GET is used for SSE streaming - we don't support it yet
	// Return 405 Method Not Allowed to indicate no SSE support
	http.Error(w, "SSE streaming not implemented", http.StatusMethodNotAllowed)
}

func (b *Bridge) handleMCPDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	// DELETE is used to terminate sessions
	sessionID := r.Header.Get("Mcp-Session-Id")
	if sessionID == "" {
		http.Error(w, "No session ID provided", http.StatusBadRequest)
		return
	}

	b.sessionMu.Lock()
	if b.sessionID == sessionID {
		log.Printf("Session terminated by client: %s\n", sessionID)
		b.sessionID = ""
		b.lastID = -1
	}
	b.sessionMu.Unlock()

	w.WriteHeader(http.StatusOK)
}

func (b *Bridge) sendJSONResponse(w http.ResponseWriter, r *http.Request, resp JSONRPCResponse) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)

	respBytes, err := json.Marshal(resp)
	if err != nil {
		log.Printf("Failed to marshal response: %v\n", err)
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}

	if *debugLog {
		log.Printf("Response: %s\n", string(respBytes))
	}

	w.Write(respBytes)
}

func isAllowedOrigin(origin string) bool {
	// Allow localhost and 127.0.0.1
	return strings.HasPrefix(origin, "http://localhost") ||
		strings.HasPrefix(origin, "http://127.0.0.1") ||
		strings.HasPrefix(origin, "https://localhost") ||
		strings.HasPrefix(origin, "https://127.0.0.1")
}

func (b *Bridge) handleRequest(ctx context.Context, req JSONRPCRequest) JSONRPCResponse {
	// Get request ID (0 for notifications, though they shouldn't reach here)
	reqID := int64(0)
	if req.ID != nil {
		reqID = *req.ID
	}

	switch req.Method {
	case "initialize":
		return b.handleInitialize(req)
	case "tools/list":
		return b.handleToolsList(req)
	case "tools/call":
		return b.handleToolsCall(ctx, req)
	default:
		return b.makeErrorResponse(reqID, ErrCodeMethodNotFound, "Method not found", req.Method)
	}
}

func (b *Bridge) handleInitialize(req JSONRPCRequest) JSONRPCResponse {
	result := InitializeResult{
		ProtocolVersion: "2024-11-05",
		Capabilities: map[string]any{
			"tools": map[string]any{},
		},
		ServerInfo: map[string]any{
			"name":    "varlink-mcp-bridge",
			"version": "0.1.0",
		},
	}

	reqID := int64(0)
	if req.ID != nil {
		reqID = *req.ID
	}

	return JSONRPCResponse{
		JSONRPC: "2.0",
		ID:      reqID,
		Result:  result,
	}
}

func (b *Bridge) handleToolsList(req JSONRPCRequest) JSONRPCResponse {
	result := ToolsListResult{
		Tools: b.tools,
	}

	reqID := int64(0)
	if req.ID != nil {
		reqID = *req.ID
	}

	return JSONRPCResponse{
		JSONRPC: "2.0",
		ID:      reqID,
		Result:  result,
	}
}

func (b *Bridge) handleToolsCall(ctx context.Context, req JSONRPCRequest) JSONRPCResponse {
	reqID := int64(0)
	if req.ID != nil {
		reqID = *req.ID
	}

	var params ToolsCallParams
	if err := json.Unmarshal(req.Params, &params); err != nil {
		return b.makeErrorResponse(reqID, ErrCodeInvalidParams, "Invalid params", err.Error())
	}

	// Find the tool and get its original Varlink method name
	var methodName string
	for _, tool := range b.tools {
		if tool.Name == params.Name {
			methodName = tool.VarlinkMethod
			break
		}
	}

	if methodName == "" {
		return b.makeErrorResponse(reqID, ErrCodeInvalidParams, "Unknown tool", params.Name)
	}

	// Call varlink method
	result, err := b.varlinkClient.Call(ctx, methodName, params.Arguments)
	if err != nil {
		return b.makeErrorResponse(reqID, ErrCodeInternal, fmt.Sprintf("Varlink call failed: %v", err), "")
	}

	// Check if result contains HTTP resources (can be at top level or under parameters)
	var resourceParams map[string]any
	if resourceType, ok := result["resource_type"].(string); ok && resourceType == "http_listing" {
		// Resource type at top level (maildir style)
		resourceParams = result
	} else if resultParams, ok := result["parameters"].(map[string]any); ok {
		if resourceType, ok := resultParams["resource_type"].(string); ok && resourceType == "http_listing" {
			// Resource type under parameters
			resourceParams = resultParams
		}
	}

	if resourceParams != nil {
		// Handle binary resources
		return b.handleResourceResponse(ctx, reqID, methodName, params.Arguments, resourceParams)
	}

	// Format normal result as MCP content
	resultJSON, _ := json.Marshal(result)
	callResult := ToolsCallResult{
		Content: []ContentItem{
			{
				Type: "text",
				Text: string(resultJSON),
			},
		},
	}

	return JSONRPCResponse{
		JSONRPC: "2.0",
		ID:      reqID,
		Result:  callResult,
	}
}

// handleResourceResponse handles responses containing binary resources
func (b *Bridge) handleResourceResponse(ctx context.Context, id int64, methodName string, originalParams map[string]any, resultParams map[string]any) JSONRPCResponse {
	// Clean old resources (older than 1 hour)
	if err := b.cache.CleanOldResources(3600); err != nil {
		log.Printf("Warning: failed to clean old resources: %v\n", err)
	}

	// Extract resources array
	resourcesRaw, ok := resultParams["resources"].([]any)
	if !ok || len(resourcesRaw) == 0 {
		return b.makeErrorResponse(id, ErrCodeInternal, "No resources found in http_listing", "")
	}

	// Extract resource paths and filenames
	type ResourceInfo struct {
		Path     string
		Filename string
		Size     int64
	}

	var resourceInfos []ResourceInfo
	var resourcePaths []string

	for _, resRaw := range resourcesRaw {
		resMap, ok := resRaw.(map[string]any)
		if !ok {
			continue
		}

		path, _ := resMap["path"].(string)
		if path == "" {
			continue
		}

		// Extract filename (prefer explicit filename field, fall back to path)
		filename := ""
		if fn, ok := resMap["filename"].(string); ok && fn != "" {
			filename = fn
		} else {
			// Extract from path
			parts := strings.Split(path, "/")
			if len(parts) > 0 && parts[len(parts)-1] != "" {
				filename = parts[len(parts)-1]
			} else {
				filename = fmt.Sprintf("resource-%d", len(resourcePaths))
			}
		}

		size, _ := resMap["size"].(float64) // JSON numbers are float64

		resourceInfos = append(resourceInfos, ResourceInfo{
			Path:     path,
			Filename: filename,
			Size:     int64(size),
		})
		resourcePaths = append(resourcePaths, path)
	}

	// Fetch all resources at once
	log.Printf("Fetching %d resources from varlink...\n", len(resourcePaths))
	resourceData, err := b.varlinkClient.FetchResources(ctx, methodName, originalParams, resourcePaths)
	if err != nil {
		return b.makeErrorResponse(id, ErrCodeInternal, fmt.Sprintf("Failed to fetch resources: %v", err), "")
	}

	// Write files to session directory and collect file paths
	var filePaths []string
	for i, info := range resourceInfos {
		data, ok := resourceData[info.Path]
		if !ok {
			log.Printf("Warning: resource %s not found in fetched data\n", info.Path)
			continue
		}

		// Write to session directory
		filePath := filepath.Join(b.sessionDir, info.Filename)
		if err := os.WriteFile(filePath, data, 0644); err != nil {
			log.Printf("Warning: failed to write file %s: %v\n", filePath, err)
			continue
		}

		filePaths = append(filePaths, filePath)
		log.Printf("Wrote resource %d/%d: %s (%d bytes)\n", i+1, len(resourceInfos), filePath, len(data))

		// Also store in cache for future reference
		_, err = b.cache.StoreResource(info.Filename, "", data, *varlinkAddress, methodName)
		if err != nil {
			log.Printf("Warning: failed to cache resource: %v\n", err)
		}
	}

	if len(filePaths) == 0 {
		return b.makeErrorResponse(id, ErrCodeInternal, "No files were successfully written", "")
	}

	// Return text content with file paths
	var responseText strings.Builder
	responseText.WriteString(fmt.Sprintf("Downloaded %d file(s) to session directory:\n\n", len(filePaths)))
	for _, path := range filePaths {
		responseText.WriteString(fmt.Sprintf("%s\n", path))
	}

	callResult := ToolsCallResult{
		Content: []ContentItem{
			{
				Type: "text",
				Text: responseText.String(),
			},
		},
	}

	return JSONRPCResponse{
		JSONRPC: "2.0",
		ID:      id,
		Result:  callResult,
	}
}

func (b *Bridge) sendError(encoder *json.Encoder, id int64, code int, message, data string) {
	resp := b.makeErrorResponse(id, code, message, data)
	encoder.Encode(resp)
}

func (b *Bridge) makeErrorResponse(id int64, code int, message, data string) JSONRPCResponse {
	return JSONRPCResponse{
		JSONRPC: "2.0",
		ID:      id,
		Error: &RPCError{
			Code:    code,
			Message: message,
			Data:    data,
		},
	}
}

func generateSessionID() string {
	// Generate session ID using timestamp + random bytes
	timestamp := time.Now().Unix()

	// Generate 4 random bytes
	randomBytes := make([]byte, 4)
	if _, err := rand.Read(randomBytes); err != nil {
		// Fallback to timestamp only if random fails
		return fmt.Sprintf("%d", timestamp)
	}

	randomHex := hex.EncodeToString(randomBytes)
	return fmt.Sprintf("%d-%s", timestamp, randomHex)
}

func buildTools(parsedIDL *idl.IDL, interfaceName string) ([]Tool, error) {
	var tools []Tool

	for _, method := range parsedIDL.Methods {
		// Build input schema
		inputSchema, err := buildInputSchemaForMethod(method)
		if err != nil {
			return nil, fmt.Errorf("failed to build schema for %s: %w", method.Name, err)
		}

		tool := Tool{
			Name:          sanitizeToolName(interfaceName, method.Name),
			Description:   method.Doc, // ✨ Documentation from varlink comments!
			InputSchema:   inputSchema,
			VarlinkMethod: method.Name, // Store original Varlink method name
		}

		tools = append(tools, tool)
	}

	return tools, nil
}