Skip to content

mcp/examples: add PostgreSQL MCP server example #70

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
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
17 changes: 17 additions & 0 deletions examples/postgres/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Example configuration for PostgreSQL MCP Server
# Copy this to .env and modify as needed

# Database connection string
DATABASE_URL=postgres://testuser:testpass@localhost:5432/testdb?sslmode=disable

# Alternative format examples:
# DATABASE_URL=postgres://username:password@hostname:5432/database_name
# DATABASE_URL=postgres://user@localhost/dbname?sslmode=require
# DATABASE_URL=postgresql://user:pass@localhost:5432/db?sslmode=disable

# For production, consider using SSL:
# DATABASE_URL=postgres://user:pass@host:5432/db?sslmode=require

# For cloud databases:
# DATABASE_URL=postgres://user:[email protected]:5432/db?sslmode=require
# DATABASE_URL=postgres://user:[email protected]:5432/db?sslmode=require
45 changes: 45 additions & 0 deletions examples/postgres/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
postgres-mcp-server

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool
*.out
*.prof

# Go workspace file
go.work

# Dependency directories
vendor/

# IDE files
.vscode/
.idea/
*.swp
*.swo
*~

# OS files
.DS_Store
Thumbs.db

# Docker volumes
postgres_data/

# Log files
*.log

# Environment files
.env
.env.local

# Distribution packages
*.tar.gz
*.zip
37 changes: 37 additions & 0 deletions examples/postgres/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Build stage
FROM golang:1.23-alpine AS builder

# Install build dependencies
RUN apk add --no-cache git

# Set working directory
WORKDIR /app

# Copy go mod files
COPY go.mod go.sum ./

# Download dependencies
RUN go mod download

# Copy source code
COPY . .

# Build the application
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o postgres-mcp-server .

# Final stage
FROM alpine:latest

# Install ca-certificates for HTTPS requests
RUN apk --no-cache add ca-certificates

WORKDIR /root/

# Copy the binary from builder stage
COPY --from=builder /app/postgres-mcp-server .

# Expose port for HTTP mode (optional)
EXPOSE 8080

# Default to stdio mode, but allow HTTP mode via environment
CMD ["./postgres-mcp-server"]
87 changes: 87 additions & 0 deletions examples/postgres/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# PostgreSQL MCP Server Makefile

.PHONY: help build test clean docker docker-compose run run-http dev

# Default target
help:
@echo "Available targets:"
@echo " build - Build the PostgreSQL MCP server binary"
@echo " test - Run tests with coverage"
@echo " clean - Clean build artifacts"
@echo " docker - Build Docker image"
@echo " docker-compose - Start development environment with Docker Compose"
@echo " run - Run server in stdio mode (requires DATABASE_URL)"
@echo " run-http - Run server in HTTP mode on :8080"
@echo " dev - Start local development with sample database"

# Build the binary
build:
go build -o postgres-mcp-server main.go

# Run tests with coverage
test:
go test -v -cover

# Clean build artifacts
clean:
rm -f postgres-mcp-server

# Build Docker image
docker:
docker build -t postgres-mcp-server .

# Start development environment
docker-compose:
docker-compose up -d

# Stop development environment
docker-compose-down:
docker-compose down -v

# Run server in stdio mode
run:
@if [ -z "$(DATABASE_URL)" ]; then \
echo "DATABASE_URL environment variable is required"; \
echo "Example: make run DATABASE_URL='postgres://user:pass@localhost:5432/db'"; \
exit 1; \
fi
go run main.go

# Run server in HTTP mode for debugging
run-http:
@if [ -z "$(DATABASE_URL)" ]; then \
echo "DATABASE_URL environment variable is required"; \
echo "Example: make run-http DATABASE_URL='postgres://user:pass@localhost:5432/db'"; \
exit 1; \
fi
go run main.go -http=:8080

# Start local development with sample database
dev: docker-compose
@echo "Waiting for PostgreSQL to start..."
@sleep 5
@echo "Development environment ready!"
@echo "Database: postgres://testuser:testpass@localhost:5432/testdb"
@echo "To run the MCP server:"
@echo " export DATABASE_URL='postgres://testuser:testpass@localhost:5432/testdb?sslmode=disable'"
@echo " make run"

# Install dependencies
deps:
go mod tidy

# Run linting (if available)
lint:
@if command -v golangci-lint >/dev/null 2>&1; then \
golangci-lint run; \
else \
echo "golangci-lint not installed, skipping..."; \
go vet ./...; \
fi

# Run all checks
check: test lint

# Package for distribution
package: clean build
tar -czf postgres-mcp-server.tar.gz postgres-mcp-server README.md init.sql docker-compose.yml Dockerfile
179 changes: 179 additions & 0 deletions examples/postgres/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
# PostgreSQL

A Model Context Protocol server that provides read-only access to PostgreSQL databases. This server enables LLMs to inspect database schemas and execute read-only queries.

## Components

### Tools

- **query**
- Execute read-only SQL queries against the connected database
- Input: `sql` (string): The SQL query to execute
- All queries are executed within a READ ONLY transaction

### Resources

The server provides schema information for each table in the database:

- **Table Schemas** (`postgres://<host>/<table>/schema`)
- JSON schema information for each table
- Includes column names and data types
- Automatically discovered from database metadata

## Configuration

### Usage with Claude Desktop

To use this server with the Claude Desktop app, add the following configuration to the "mcpServers" section of your `claude_desktop_config.json`:

### Docker

- When running Docker on macOS, use `host.docker.internal` if the PostgreSQL server is running on the host network (e.g. localhost)
- Username/password can be added to the PostgreSQL URL with `postgresql://user:password@host:port/db-name`

```json
{
"mcpServers": {
"postgres": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"mcp/postgres-go",
"postgresql://host.docker.internal:5432/mydb"
]
}
}
}
```

### Go Binary

```json
{
"mcpServers": {
"postgres": {
"command": "/path/to/postgres-mcp-server",
"args": ["postgresql://localhost/mydb"]
}
}
}
```

Replace `/mydb` with your database name and `/path/to/postgres-mcp-server` with the actual path to your built binary.

### Usage with VS Code

For manual installation, add the following JSON block to your User Settings (JSON) file in VS Code. You can do this by pressing `Ctrl + Shift + P` and typing `Preferences: Open User Settings (JSON)`.

Optionally, you can add it to a file called `.vscode/mcp.json` in your workspace. This will allow you to share the configuration with others.

> Note that the `mcp` key is not needed in the `.vscode/mcp.json` file.

### Docker

**Note**: When using Docker and connecting to a PostgreSQL server on your host machine, use `host.docker.internal` instead of `localhost` in the connection URL.

```json
{
"mcp": {
"inputs": [
{
"type": "promptString",
"id": "pg_url",
"description": "PostgreSQL URL (e.g. postgresql://user:[email protected]:5432/mydb)"
}
],
"servers": {
"postgres": {
"command": "docker",
"args": ["run", "-i", "--rm", "mcp/postgres-go", "${input:pg_url}"]
}
}
}
}
```

### Go Binary

```json
{
"mcp": {
"inputs": [
{
"type": "promptString",
"id": "pg_url",
"description": "PostgreSQL URL (e.g. postgresql://user:pass@localhost:5432/mydb)"
}
],
"servers": {
"postgres": {
"command": "/path/to/postgres-mcp-server",
"args": ["${input:pg_url}"]
}
}
}
}
```

## Development

### Quick Start

1. Start the development environment:

```bash
make dev
```

2. Run the server:

```bash
export DATABASE_URL="postgres://testuser:testpass@localhost:5432/testdb?sslmode=disable"
go run main.go
```

### Building

Go binary:

```bash
go build -o postgres-mcp-server main.go
```

Docker:

```bash
docker build -t mcp/postgres-go .
```

### Testing

Run the test suite:

```bash
go test -v -cover
```

Or use the Makefile:

```bash
make test
```

### Environment Variables

The server can be configured using environment variables:

- `DATABASE_URL`: PostgreSQL connection string (required)

Example:

```bash
export DATABASE_URL="postgres://user:password@localhost:5432/database?sslmode=disable"
```

## License

This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.
Loading