Skip to content

jgavinray/mcp-go

Repository files navigation

MCP Go Server

A secure, self-hosted Model Context Protocol (MCP) server written in Go with comprehensive data governance features. This server gives you full control over your data, ensuring privacy, security, and compliance.

Features

  • 🔒 Data Governance: Complete audit logging, access control, and data retention policies
  • 🛡️ Security: Authentication, encryption, and secure configuration management
  • 📊 Monitoring: Built-in metrics and structured logging
  • 🔧 Extensible: Easy to add custom tools and resources
  • Performance: Efficient concurrent request handling
  • 📝 Audit Trail: Comprehensive logging of all operations

Prerequisites

  • Go 1.21 or later
  • Basic understanding of MCP (Model Context Protocol)

Installation

  1. Clone the repository:
git clone <your-repo-url>
cd mcp-go
  1. Install dependencies:
go mod download
  1. Copy the example environment file:
cp .env.example .env
  1. Edit .env and configure your settings (especially API_KEY if AUTH_ENABLED=true)

Configuration

The server is configured via environment variables. See .env.example for all available options:

Key Configuration Options

  • AUTH_ENABLED: Enable/disable authentication (default: true)
  • API_KEY: Secret key for authentication (required if auth enabled)
  • AUDIT_ENABLED: Enable audit logging (default: true)
  • AUDIT_LOG_PATH: Path to audit log file (default: ./audit.log)
  • DATA_RETENTION_DAYS: Days to retain audit data (default: 90)
  • ENCRYPTION_ENABLED: Enable data encryption (default: true)
  • LOG_LEVEL: Logging level (debug, info, warn, error)
  • LOG_FORMAT: Log format (json or console)

Usage

Running the Server

The MCP server communicates via stdin/stdout (standard MCP protocol):

make run

Or build and run:

make build
./bin/mcp-server

Integration with MCP Clients

The server follows the MCP protocol and can be integrated with any MCP-compatible client. Example configuration for Claude Desktop:

{
  "mcpServers": {
    "mcp-go": {
      "command": "/path/to/bin/mcp-server",
      "env": {
        "API_KEY": "your-api-key",
        "AUDIT_ENABLED": "true",
        "AUDIT_LOG_PATH": "./audit.log"
      }
    }
  }
}

Or create a .env file in the same directory as the binary with your configuration.

Available Tools

echo

Echoes back the input message.

Parameters:

  • message (string, required): The message to echo

Example:

{
  "message": "Hello, World!"
}

calculate

Performs basic arithmetic operations.

Parameters:

  • operation (string, required): One of "add", "subtract", "multiply", "divide"
  • a (number, required): First number
  • b (number, required): Second number

Example:

{
  "operation": "add",
  "a": 10,
  "b": 5
}

system_info

Returns system information and governance metrics.

Parameters: None

Available Resources

config://server

Returns current server configuration (read-only).

metrics://governance

Returns current data governance metrics.

Data Governance

Audit Logging

All operations are logged to the audit log file (configurable via AUDIT_LOG_PATH). Each entry includes:

  • Timestamp
  • Action type
  • Tool/resource accessed
  • Success/failure status
  • Error messages (if any)
  • Data size
  • Request ID

Access Control

The server supports authentication via API keys. When AUTH_ENABLED=true, all requests must include a valid API key.

Data Retention

Audit logs are retained according to DATA_RETENTION_DAYS. Automatic cleanup runs daily.

Encryption

When ENCRYPTION_ENABLED=true, sensitive data can be encrypted (implementation can be extended with proper encryption libraries).

Adding Custom Tools

To add a custom tool, edit internal/tools/tools.go and add a new tool definition:

// Define your tool arguments struct
type MyToolArgs struct {
    Param1 string `json:"param1" jsonschema:"description=Parameter description,required"`
}

// Register the tool
if err := server.RegisterTool("my_tool", "Description of my tool", func(ctx context.Context, args MyToolArgs) (*mcp_golang.ToolResponse, error) {
    // Your tool logic here
    // Don't forget to audit!
    gov.Audit(AuditEntry{
        Action:  "tool_execution",
        Tool:    "my_tool",
        Success: true,
    })
    
    result := map[string]interface{}{
        "result": "your result",
    }
    resultJSON, _ := json.Marshal(result)
    return mcp_golang.NewToolResponse(mcp_golang.NewTextContent(string(resultJSON))), nil
}); err != nil {
    return fmt.Errorf("failed to register my_tool: %w", err)
}

Adding Custom Resources

To add a custom resource, edit internal/resources/resources.go:

if err := server.RegisterResource(
    "resource://my-resource",
    "My Resource",
    "Description of my resource",
    "application/json",
    func(ctx context.Context) (*mcp_golang.ResourceResponse, error) {
        // Your resource logic here
        gov.Audit(AuditEntry{
            Action:   "resource_access",
            Resource: "resource://my-resource",
            Success:  true,
        })
        
        data := map[string]interface{}{
            "data": "your data",
        }
        dataJSON, _ := json.Marshal(data)
        return mcp_golang.NewResourceResponse(
            mcp_golang.NewTextEmbeddedResource("resource://my-resource", string(dataJSON), "application/json"),
        ), nil
    },
); err != nil {
    return fmt.Errorf("failed to register resource: %w", err)
}

<|tool▁calls▁begin|><|tool▁call▁begin|> todo_write

Security Best Practices

  1. Always set a strong API_KEY when enabling authentication
  2. Restrict ALLOWED_ORIGINS to specific domains in production
  3. Enable audit logging to track all operations
  4. Regularly review audit logs for suspicious activity
  5. Keep dependencies updated with go get -u ./...
  6. Use encryption for sensitive data in transit and at rest
  7. Implement rate limiting for production deployments
  8. Monitor metrics regularly for anomalies

Development

Project Structure

The project follows standard Go project layout:

mcp-go/
├── cmd/
│   └── mcp-server/          # Main application entry point
│       └── main.go
├── internal/                 # Private application code
│   ├── config/              # Configuration management
│   ├── governance/           # Data governance and audit logging
│   ├── logger/              # Logging setup
│   ├── resources/           # MCP resource definitions
│   ├── security/            # Security utilities
│   ├── server/              # MCP server setup
│   └── tools/               # MCP tool definitions
├── bin/                     # Build output
├── go.mod                   # Go module file
├── env.example              # Example configuration
├── PROJECT_STRUCTURE.md      # Detailed structure documentation
└── README.md                # This file

See PROJECT_STRUCTURE.md for detailed information about the project organization.

Testing

go test ./...

Building

go build -o mcp-go-server

Troubleshooting

Server won't start

  • Check that all required environment variables are set
  • Verify API_KEY is set if AUTH_ENABLED=true
  • Check log output for specific error messages

Tools not working

  • Verify tool registration in tools.go
  • Check audit logs for error details
  • Ensure input schema matches expected format

Audit logs not being created

  • Check AUDIT_LOG_PATH is writable
  • Verify AUDIT_ENABLED=true
  • Check file permissions

License

[Specify your license here]

Contributing

[Your contribution guidelines]

Support

[Your support information]

About

Personal MCP server so I can monitor how my data is used.

Resources

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published