Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,19 @@ go build -o bin/mcp-dap-server

The server uses stdio transport, allowing AI agents to spawn it on-demand. Configure your MCP client with the path to the binary.

> [!IMPORTANT]
> A debugger can launch programs, attach to processes, evaluate target code,
> inspect secrets, and alter or terminate a debuggee. Run this server only for a
> trusted, single-user MCP client under a least-privileged OS account. The stdio
> server has no HTTP listener or multi-tenant authorization layer. Delve's
> internal DAP socket is always bound to loopback.

Persistent server logging is disabled by default. Set `MCP_DAP_LOG=1` to create
a unique private log in the OS temporary directory. It is capped at 8 MiB and
retained until manually deleted. Explicit protocol and GDB tool logs reject
existing files; treat them as sensitive. GDB tool logs are written directly by
GDB and are not size-capped.

### Example MCP Client Configuration

This configuration works with [Gemini CLI](https://developers.google.com/gemini-code-assist/docs/use-agentic-chat-pair-programmer#configure-mcp-servers) and similar MCP clients:
Expand Down Expand Up @@ -92,7 +105,8 @@ Start a debugging session. Supports four modes:
- `processId` (number): Process ID (required for attach mode)
- `breakpoints` (array): Breakpoints to set before running (file:line or function name)
- `stopOnEntry` (boolean): Stop at program entry point
- `port` (number): DAP server port
- `port` (number): optional numeric Delve port (`0` chooses an ephemeral
loopback port; external bind addresses are not accepted)

Returns full context (location, stack trace, variables) when stopped.

Expand Down
95 changes: 70 additions & 25 deletions backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import (
"bufio"
"fmt"
"io"
"net"
"os"
"os/exec"
"strings"
"time"
)

// DebuggerBackend abstracts the debugger-specific logic for spawning a DAP
Expand All @@ -21,6 +23,8 @@ type DebuggerBackend interface {

// TransportMode returns "tcp" or "stdio" indicating how to connect.
TransportMode() string
// StdioPipes returns the adapter pipes for stdio transports.
StdioPipes() (stdout io.ReadCloser, stdin io.WriteCloser)

// AdapterID returns the DAP adapter identifier for InitializeRequest.
AdapterID() string
Expand All @@ -47,7 +51,17 @@ type delveBackend struct{}
// The port should be in ":PORT" format (e.g. ":0" for auto-assign).
// It waits for the server to report its listen address on stdout.
func (b *delveBackend) Spawn(port string, stderrWriter io.Writer) (*exec.Cmd, string, error) {
cmd := exec.Command("dlv", "dap", "--listen", port, "--log", "--log-output", "dap")
listen, err := delveListenAddress(port)
if err != nil {
return nil, "", err
}
cmd := exec.Command("dlv", "dap", "--listen", listen)
return startDelve(cmd, stderrWriter, 10*time.Second)
}

// startDelve bounds startup and continues draining stdout after the announcement.
// The caller owns Wait after success; on failure this function reaps the child.
func startDelve(cmd *exec.Cmd, stderrWriter io.Writer, timeout time.Duration) (*exec.Cmd, string, error) {
// Send adapter stderr to the provided writer, never to os.Stderr.
// With MCP stdio transport, os.Stderr is a pipe that can fill and block.
cmd.Stderr = stderrWriter
Expand All @@ -59,39 +73,62 @@ func (b *delveBackend) Spawn(port string, stderrWriter io.Writer) (*exec.Cmd, st
return nil, "", err
}

// Wait for server to start and parse actual listen address
r := bufio.NewReader(stdout)
var listenAddr string
for {
s, err := r.ReadString('\n')
if err != nil {
cmd.Process.Kill()
cmd.Wait()
return nil, "", err
}
if strings.HasPrefix(s, "DAP server listening at") {
// Parse address from "DAP server listening at: 127.0.0.1:PORT"
parts := strings.SplitN(s, ": ", 2)
if len(parts) == 2 {
listenAddr = strings.TrimSpace(parts[1])
type result struct {
address string
err error
}
ready := make(chan result, 1)
go func() {
scanner := bufio.NewScanner(stdout) // bounds pre-announcement line size
for scanner.Scan() {
if address, ok := strings.CutPrefix(scanner.Text(), "DAP server listening at: "); ok {
host, port, err := net.SplitHostPort(address)
ip := net.ParseIP(host)
if err != nil || ip == nil || !ip.IsLoopback() {
ready <- result{err: fmt.Errorf("invalid Delve listen address")}
return
}
if _, err := delveListenAddress(port); err != nil || port == "0" {
ready <- result{err: fmt.Errorf("invalid Delve listen port")}
return
}
ready <- result{address: address}
_, _ = io.Copy(io.Discard, stdout)
return
}
break
}
err := scanner.Err()
if err == nil {
err = io.ErrUnexpectedEOF
}
ready <- result{err: err}
}()
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case r := <-ready:
if r.err == nil {
return cmd, r.address, nil
}
err = r.err
case <-timer.C:
err = fmt.Errorf("Delve startup timed out after %s", timeout)
}
if listenAddr == "" {
cmd.Process.Kill()
cmd.Wait()
return nil, "", fmt.Errorf("failed to parse DAP server listen address")
}

return cmd, listenAddr, nil
_ = cmd.Process.Kill()
_ = stdout.Close()
_ = cmd.Wait()
return nil, "", err
}

// TransportMode returns "tcp" because Delve communicates over a TCP socket.
func (b *delveBackend) TransportMode() string {
return "tcp"
}

func (b *delveBackend) StdioPipes() (io.ReadCloser, io.WriteCloser) {
return nil, nil
}

// AdapterID returns "go" for the Delve debug adapter.
func (b *delveBackend) AdapterID() string {
return "go"
Expand Down Expand Up @@ -164,10 +201,15 @@ func (g *gdbBackend) Spawn(port string, stderrWriter io.Writer) (*exec.Cmd, stri
if gdbPath == "" {
gdbPath = "gdb"
}
args := []string{"-i", "dap"}
// Ignore user/project init files and target-supplied auto-load scripts.
// Explicit debugger commands remain available; this is not a sandbox.
args := []string{"-nx", "-iex", "set auto-load off", "-i", "dap"}
// Disable terminal styling — ANSI escapes have no place in DAP JSON responses.
args = append([]string{"-iex", "set style enabled off"}, args...)
if g.toolLogPath != "" {
if err := prepareGDBLog(g.toolLogPath); err != nil {
return nil, "", fmt.Errorf("unsafe GDB log path: %w", err)
}
args = append([]string{"-iex", "set debug dap-log-file " + g.toolLogPath}, args...)
}
cmd := exec.Command(gdbPath, args...)
Expand All @@ -179,13 +221,16 @@ func (g *gdbBackend) Spawn(port string, stderrWriter io.Writer) (*exec.Cmd, stri
}
stdout, err := cmd.StdoutPipe()
if err != nil {
_ = stdin.Close()
return nil, "", fmt.Errorf("failed to create stdout pipe: %w", err)
}

g.stdin = stdin
g.stdout = stdout

if err := cmd.Start(); err != nil {
_ = stdin.Close()
_ = stdout.Close()
return nil, "", fmt.Errorf("failed to start gdb: %w (is GDB 14+ installed?)", err)
}

Expand Down
8 changes: 8 additions & 0 deletions backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,14 @@ func TestGDBBackendLaunchArgs(t *testing.T) {
if _, ok := args["miDebuggerPath"]; ok {
t.Error("unexpected miDebuggerPath key (cpptools artifact)")
}

withoutArgs, err := backend.LaunchArgs("binary", "/path/to/prog", false, nil)
if err != nil {
t.Fatalf("LaunchArgs without program args: %v", err)
}
if _, ok := withoutArgs["args"]; ok {
t.Errorf("empty program args should be omitted, got: %#v", withoutArgs["args"])
}
}

func TestGDBBackendSourceModeError(t *testing.T) {
Expand Down
34 changes: 19 additions & 15 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,32 +5,34 @@ import (
"io"
"log"
"os"
"path/filepath"

"github.com/modelcontextprotocol/go-sdk/mcp"
)

var version = "dev"

func main() {
if err := run(); err != nil {
os.Exit(1)
}
}

func run() error {
// Log only to a file — never to stderr. With MCP stdio transport,
// stderr is a pipe to the MCP client. If the pipe buffer fills
// (from our logs or the DAP adapter's stderr), any write blocks
// the goroutine and hangs the server.
logPath := filepath.Join(os.TempDir(), "mcp-dap-server.log")
var logWriter io.Writer
logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
// Discard logs if we can't open the file — do NOT fall back to stderr
logWriter = io.Discard
log.SetOutput(logWriter)
} else {
logWriter = logFile
log.SetOutput(logWriter)
defer logFile.Close()
var logWriter io.Writer = io.Discard
// Opt-in diagnostics are unique, private, capped at 8 MiB and retained
// in the OS temporary directory until the operator deletes them.
if os.Getenv("MCP_DAP_LOG") == "1" {
if logFile, err := openPrivateLog(""); err == nil {
logWriter = newBoundedLogWriter(logFile)
defer logFile.Close()
}
}

log.Printf("mcp-dap-server starting (log file: %s)", logPath)
log.SetOutput(logWriter)
log.Printf("mcp-dap-server starting")

// Create MCP server
implementation := mcp.Implementation{
Expand All @@ -45,6 +47,8 @@ func main() {
registerPrompts(server)

if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil {
log.Fatalf("server error: %v", err)
log.Printf("server error: %v", err)
return err
}
return nil
}
99 changes: 99 additions & 0 deletions security.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package main

import (
"fmt"
"io"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
)

const maxLogBytes = 8 << 20

// openPrivateLog never replaces an existing file (including a symlink).
// Logs are retained until the operator deletes them. Callers must close them.
func openPrivateLog(path string) (*os.File, error) {
if path == "" {
return os.CreateTemp("", "mcp-dap-*.log")
}
return os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
}

type boundedLogWriter struct {
mu sync.Mutex
writer io.Writer
remaining int
}

func newBoundedLogWriter(w io.Writer) io.Writer {
return &boundedLogWriter{writer: w, remaining: maxLogBytes}
}

func (w *boundedLogWriter) Write(p []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
n := len(p)
if len(p) > w.remaining {
p = p[:w.remaining]
}
if len(p) > 0 {
written, err := w.writer.Write(p)
w.remaining -= written
if err != nil {
return written, err
}
if written != len(p) {
return written, io.ErrShortWrite
}
}
return n, nil
}

// Only a numeric port, optionally prefixed by ':', is accepted. A caller
// cannot change the loopback-only transport policy by supplying a host.
func delveListenAddress(port string) (string, error) {
port = strings.TrimPrefix(port, ":")
if port == "" {
return "", fmt.Errorf("Delve port must be numeric (0-65535)")
}
for _, c := range port {
if c < '0' || c > '9' {
return "", fmt.Errorf("Delve port must be numeric (0-65535)")
}
}
n, err := strconv.ParseUint(port, 10, 16)
if err != nil {
return "", fmt.Errorf("invalid Delve port: %w", err)
}
return net.JoinHostPort("127.0.0.1", strconv.Itoa(int(n))), nil
}

// GDB interprets this value as command text, not as a shell argument.
// Deliberately support only a literal absolute pathname without whitespace,
// quoting or command metacharacters. Its parent must be private because GDB
// reopens the file by name rather than accepting our descriptor.
func prepareGDBLog(path string) error {
if !filepath.IsAbs(path) {
return fmt.Errorf("GDB log path must be absolute")
}
for _, c := range path {
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("/._-", c)) {
return fmt.Errorf("GDB log path contains unsupported characters")
}
}
dir, err := os.Stat(filepath.Dir(path))
if err != nil {
return err
}
if dir.Mode().Perm()&0077 != 0 {
return fmt.Errorf("GDB log parent directory must be private (0700)")
}
f, err := openPrivateLog(path)
if err != nil {
return err
}
return f.Close()
}
Loading
Loading