In this guide, you run a demo PostgreSQL database in a beam and give an MCP client SQL access to it through Teleport. tsh runs a local MCP server that queries the database with your Teleport identity, so the client never sees a database password or certificate.
Language models can run any query a database user is allowed to run, so the client connects as a database user that can only read. Teleport allows only that user, and PostgreSQL rejects writes.
You connect in one of two ways:
- From your dev computer: your MCP client runs locally and starts
tsh mcp db start. - From inside a beam: your agent runs in a separate agent beam, which reaches the database with the role you delegate to it.
How it works
- The database beam runs from the
beams-postgresphase. Its image contains the PostgreSQL server, sample data and the Teleport agent. On start, the beam signs its own PostgreSQL server certificate, creates a single-usebound_keypairjoin token and starts the Teleport Database Service. The service connects out to your cluster. - Your MCP client starts
tsh mcp db startas a local stdio server, with a URI that names the database, the database user and the database name. - When the client calls a tool,
tshconnects to the database through the Teleport proxy. Teleport checks your roles for the database, user and name, then forwards the query.
The MCP server has two tools:
| Tool | What it does |
|---|---|
teleport_list_databases |
Lists the databases configured for this MCP server, with their URIs |
teleport_postgres_query |
Runs a SQL query on one of those databases |
The configured databases are also available as MCP resources, which some clients let you attach to a conversation as context.
Prerequisites
- A cluster with Teleport Beams enabled.
- Permission to create roles and edit your own user, for example with the
editorrole. tsh,tctlandjq.- An MCP client that can start a stdio command. The examples use Claude Code. On your dev computer, install it and sign in. Beams include Claude Code, already connected to the LLM gateway.
Install the client tools and sign in
Beams is a Teleport project and uses official Teleport client tools.
The client tools include tsh to sign in and run commands, and tctl to administer your cluster if you have permission.
Cluster: example.beams.run. Edit this example to use your cluster name.
Install version 18.11.10 of the client:
Download and open the macOS installer, then follow its instructions.
curl -O https://cdn.teleport.dev/teleport-tools-18.11.10.pkg
open teleport-tools-18.11.10.pkgFor Linux x86-64, download and install the client tools:
curl -O https://cdn.teleport.dev/teleport-v18.11.10-linux-amd64-bin.tar.gz
tar -xzf teleport-v18.11.10-linux-amd64-bin.tar.gz
sudo ./teleport/installFor Windows x86-64, run these commands in PowerShell. Add the extraction directory ($env:LOCALAPPDATA\Teleport) to your user PATH to use tsh in future terminals; the last command adds it to this terminal's PATH.
Invoke-WebRequest -Uri https://cdn.teleport.dev/teleport-v18.11.10-windows-amd64-bin.zip -OutFile teleport.zip
Expand-Archive -Path teleport.zip -DestinationPath "$env:LOCALAPPDATA\Teleport" -Force
$env:Path += ";$env:LOCALAPPDATA\Teleport"Follow the official client tools install guide for other versions and architectures.
Check that you’re running v18.11.10 of the client with tsh version.
tsh versionI sign in without a password (e.g. a passkey).
tsh login --proxy='example.beams.run' --auth=passwordlessI have a password & MFA set up for my account:
Replace you@example.com with your Teleport username.
tsh login --proxy='example.beams.run' --user=you@example.comI sign in with SSO (e.g. Okta, GitHub, SAML).
tsh login --proxy='example.beams.run'1. Create roles
You need two roles. The database beam uses postgres-demo-host, and the agent uses read-only-demo-postgres. To learn how the role fields work, see Access control.
-
Create
postgres-demo-host.yaml. This role lets the database beam sign database server certificates and write join tokens.tctl create -fneeds bothcreateandupdateto write a bound keypair token:kind: role version: v8 metadata: name: postgres-demo-host spec: allow: rules: - resources: [database_certificate] verbs: [create] - resources: [token] verbs: [create, update] -
Create
read-only-demo-postgres.yaml. This role allows access to the demo database only as thereadonlyuser. It also allows access to your cluster's LLM endpoints, so an agent in a beam can run:kind: role version: v8 metadata: name: read-only-demo-postgres spec: allow: db_labels: service: beams-postgres db_users: - readonly db_names: - postgres app_labels: teleport.internal/beams/app-type: llm -
Create both roles:
tctl create -f postgres-demo-host.yaml tctl create -f read-only-demo-postgres.yaml -
You can delegate only roles that you hold. Add both roles to your user while keeping your existing roles:
me=$(tsh status --format=json | jq -r .active.username) roles=$(tctl get "users/$me" --format=json | jq -r '.[0].spec.roles | join(",")') tctl users update "$me" --set-roles="$roles,postgres-demo-host,read-only-demo-postgres" -
Log in again, so that your session includes the new roles.
2. Build the database phase
Save the following as phase.yaml. Change only the env values to adapt it:
| Setting | Default | Meaning |
|---|---|---|
TELEPORT_AGENT_VERSION |
empty | Agent version to install. Empty uses the version your cluster recommends. |
DB_NAME |
beams-postgres |
Database name in tsh db ls and in its VNet hostname. |
DB_LABELS |
service=beams-postgres |
Comma-separated database labels. If you change them, change db_labels in read-only-demo-postgres to match. |
JOIN_WINDOW |
10 minutes |
Time the Database Service has to join after the beam creates its token. |
version: v1
metadata:
name: beams-postgres
commands:
- comment: Install the PostgreSQL server
shell: apt-get update && apt-get install -y --no-install-recommends postgresql
- comment: Install the Teleport agent for this cluster
env:
# Leave empty to use the agent version your cluster recommends.
- name: TELEPORT_AGENT_VERSION
value: ""
shell: |
set -eu
find=$(curl -fsS "https://$TELEPORT_PROXY/v1/webapi/find")
version=${TELEPORT_AGENT_VERSION:-$(printf '%s' "$find" | jq -er .auto_update.agent_version)}
version=${version#v}
flavor=teleport
[ "$(printf '%s' "$find" | jq -r .edition)" = ent ] && flavor=teleport-ent
tarball="$flavor-v$version-linux-$(dpkg --print-architecture)-bin.tar.gz"
cd "$(mktemp -d)"
curl -fsSLO "https://cdn.teleport.dev/$tarball"
curl -fsSL "https://cdn.teleport.dev/$tarball.sha256" | sha256sum --check -
tar -xzf "$tarball" "$flavor/teleport"
# Install only the agent; keep the beam's own tsh, tctl and tbot.
install -D -m 755 "$flavor/teleport" /opt/teleport/bin/teleport
/opt/teleport/bin/teleport version
- comment: Initialize a database with sample data
shell: |
set -eu
ln -sfn "$(ls -d /usr/lib/postgresql/*/bin | sort -V | tail -n 1)" /opt/postgres
rm -rf /var/lib/beams-postgres
install -d -o beams -g beams /var/lib/beams-postgres
cd /var/lib/beams-postgres
runuser -u beams -- /opt/postgres/initdb -D data -U postgres --auth-local=trust
runuser -u beams -- /opt/postgres/pg_ctl -D data -o "-c listen_addresses='' -k /tmp" -w start
runuser -u beams -- /opt/postgres/psql -h /tmp -U postgres -v ON_ERROR_STOP=1 <<'SQL'
CREATE TABLE users (id INT PRIMARY KEY, name TEXT, ssn TEXT);
INSERT INTO users (id, name, ssn) VALUES (123, 'alice', '000-00-0000');
CREATE ROLE readonly LOGIN;
GRANT CONNECT ON DATABASE postgres TO readonly;
GRANT SELECT ON users TO readonly;
SQL
runuser -u beams -- /opt/postgres/pg_ctl -D data -w stop
# Local sockets trust the beam user; TCP clients need a certificate.
printf '%s\n' 'local all all trust' 'hostssl all all 127.0.0.1/32 cert' 'hostssl all all ::1/128 cert' > data/pg_hba.conf
services:
- name: database-setup
context: runtime
env:
# Name shown in tsh db ls and used in VNet hostnames.
- name: DB_NAME
value: beams-postgres
# Comma-separated labels. read-only-demo-postgres matches service=beams-postgres.
- name: DB_LABELS
value: service=beams-postgres
# Time allowed for the Database Service to join after the token is created.
- name: JOIN_WINDOW
value: 10 minutes
shell: |
set -eu
. /etc/environment
# Wait for the beam's tbot to deliver this beam's identity.
timeout 120 sh -c 'until [ -s ~/.tsh/current-profile ]; do sleep 1; done'
state=$HOME/.beams-postgres
install -d -m 700 "$state"
cd "$state"
token="beams-postgres-$BEAM_ID"
# Sign the certificate and create the single-use join token on first
# start only. A restart reuses the identity the agent already holds.
if [ ! -f teleport.yaml ]; then
tctl auth sign --format=db --host=localhost --ttl=12h --out=server
(umask 077; head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' > secret)
cat > token.yaml <<EOF
kind: token
version: v2
metadata:
name: $token
expires: "$(date -u -d '+12 hours' +%Y-%m-%dT%H:%M:%SZ)"
spec:
roles: [Db]
join_method: bound_keypair
bound_keypair:
onboarding:
registration_secret: "$(cat secret)"
must_register_before: "$(date -u -d "+$JOIN_WINDOW" +%Y-%m-%dT%H:%M:%SZ)"
recovery:
limit: 1
mode: standard
EOF
tctl create -f token.yaml
rm token.yaml
fi
labels=$(printf '%s' "$DB_LABELS" | tr ',' '\n' | sed -n 's/^ *\([^=]*\)=\(.*\)$/ \1: "\2"/p')
cat > teleport.yaml.tmp <<EOF
version: v3
teleport:
nodename: $DB_NAME
data_dir: $state/teleport
proxy_server: $TELEPORT_PROXY
join_params:
method: bound_keypair
token_name: $token
bound_keypair:
registration_secret_path: $state/secret
auth_service: { enabled: false }
proxy_service: { enabled: false }
ssh_service: { enabled: false }
db_service:
enabled: true
databases:
- name: $DB_NAME
protocol: postgres
uri: localhost:5432
static_labels:
$labels
EOF
mv teleport.yaml.tmp teleport.yaml
- name: postgres
context: runtime
shell: |
set -eu
timeout 180 sh -c 'until [ -f ~/.beams-postgres/teleport.yaml ]; do sleep 1; done'
exec /opt/postgres/postgres -D /var/lib/beams-postgres/data \
-c listen_addresses=localhost -c unix_socket_directories=/tmp \
-c ssl=on \
-c ssl_cert_file="$HOME/.beams-postgres/server.crt" \
-c ssl_key_file="$HOME/.beams-postgres/server.key" \
-c ssl_ca_file="$HOME/.beams-postgres/server.cas"
- name: teleport-db
context: runtime
shell: |
set -eu
timeout 180 sh -c 'until [ -f ~/.beams-postgres/teleport.yaml ]; do sleep 1; done'
exec /opt/teleport/bin/teleport start --config="$HOME/.beams-postgres/teleport.yaml"The commands run as root when the phase builds. They save the following in the image:
- The PostgreSQL server from the Debian packages.
- The
teleportbinary, at the agent version and edition your cluster reports. Only this binary is installed, because the beam's owntsh,tctlandtbotmust stay in place. - A data directory with an
alicerow and areadonlyuser that can only read it.
The phase rebuilds every 24 hours, so security updates and new agent versions arrive without changes to the file.
The services run as the beam user, only in beams started from the phase (context: runtime). database-setup waits for tbot, then uses tctl to perform the following steps:
- Sign a server certificate for
localhost. It's valid for longer than the beam's 11 hours lifetime, so it never needs renewal. - Generate a random registration secret, readable only by the beam user.
- Create a
bound_keypairtoken named after the beam's ID, with theDbrole. The secret works once, and only untilJOIN_WINDOWends. The token expires an hour after the beam does. - Write the Database Service configuration.
These steps run on first start only. A restart reuses the certificate and the identity the agent already holds.
postgres and teleport-db start once that configuration exists. PostgreSQL accepts TCP connections only from clients with a certificate signed by your cluster's database client CA.
These steps are background services, not pre-start services, because a beam's identity is delivered after its pre-start services finish.
Build the phase:
tsh phase apply -f phase.yamlThe command streams build logs and returns when the image is ready.
3. Start the database beam
Start a beam from the phase, delegating only postgres-demo-host:
tsh beams add --phase=beams-postgres --roles=postgres-demo-host --no-consoleThe database registers within a minute:
tsh db lsName Description Allowed Users Labels Connect
-------------- ----------- ------------- ---------------------- -------
beams-postgres [readonly] service=beams-postgresIf it doesn't appear, read the service logs from inside the database beam, for example tsh beams exec <beam> -- beamctl logs database-setup.
Run one database beam per DB_NAME at a time, because each registers that name. Writes to the database are lost when the beam ends, after at most 11 hours. A new beam starts again from the sample data.
4. Connect from your dev computer
Your user holds read-only-demo-postgres from step 1, so it can reach the database as readonly.
-
Confirm that
tshcan use the database user and name the MCP server will use:tsh db connect --db-user=readonly --db-name=postgres beams-postgresRun
SELECT * FROM users;and quit with\q. This needspsqlon your dev computer. Skip this step if you don’t have it. -
In a project directory, add the database to the project’s Claude Code configuration:
tsh mcp db config --db-user=readonly --db-name=postgres --client-config=.mcp.json beams-postgresAdded database "beams-postgres" on the client configuration at: .mcp.json Teleport database access MCP server is named "teleport-databases" in this configuration.The file starts
tsh mcp db startwith a URI such asteleport://clusters/CLUSTER_NAME/databases/beams-postgres?dbName=postgres&dbUser=readonly.For other clients, change
--client-config:Client --client-configvalueClaude Desktop claudeCursor, global configuration cursorCursor project PROJECT_DIR/.cursor/mcp.jsonVS Code project PROJECT_DIR/.vscode/mcp.jsonWithout
--client-config, the command prints the configuration, which you can adapt for any client that starts stdio servers. Restart Claude Desktop or Cursor after the update. To serve several databases from one MCP server, run the command once for each database. It adds each URI to the sameteleport-databasesentry. -
Start Claude Code in the project directory and approve the
teleport-databasesserver when it asks. Then check that the server is connected. The output looks similar to this:claude mcp listteleport-databases: /usr/local/bin/tsh mcp db start teleport://clusters/CLUSTER_NAME/databases/beams-postgres?dbName=postgres&dbUser=readonly - ✔ Connected -
Ask Claude Code:
Using the teleport-databases MCP tools, read alice's SSN from the users table, then try to update it to 999-99-9999.The query returns the row, and the update fails:
ERROR: permission denied for table users (SQLSTATE 42501)
5. Connect from inside a beam
An agent beam reaches the database with the roles you delegate, not your own. Inside a beam, tsh is already signed in as the beam identity.
-
Start the agent beam with only the read-only role, and open its shell:
tsh beams add --roles=read-only-demo-postgres -
Inside the beam, add the database MCP server to Claude Code:
claude mcp add teleport-databases -- tsh mcp db start "teleport://clusters/$TELEPORT_CLUSTER/databases/beams-postgres?dbName=postgres&dbUser=readonly" claude mcp list -
Start Claude Code in a mode that skips permission prompts. Teleport RBAC and the
readonlydatabase user still limit everything it does.claude --dangerously-skip-permissions -
Enter the following prompt:
Access the PostgreSQL database with name beams-postgres through the teleport-databases MCP tools. Retrieve the SSN of user alice and update it to 999-99-9999.
The agent finds the SSN but can’t change it:
- PostgreSQL rejects the update with
permission denied for table users. - If the agent edits the URI to use another database user, Teleport rejects the connection with
access to db denied.
The agent may then file a Just-in-Time access request for write access. Nothing changes unless a reviewer approves the request.
Scope access for your own databases
To use the MCP server with a real database, give it the narrowest access that works:
-
Create a database user with only the permissions the model needs. For read-only access in PostgreSQL:
CREATE ROLE mcp_read_only WITH LOGIN; GRANT CONNECT ON DATABASE my_database TO mcp_read_only; GRANT USAGE ON SCHEMA public TO mcp_read_only; GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_read_only;For Amazon RDS with IAM authentication, also run
GRANT rds_iam TO mcp_read_only;. -
In the role you delegate to an agent, allow only that user in
db_users, and list only the databases and names it needs indb_labelsanddb_names. -
For finer control, use automatic user provisioning or database access controls.
teleport_postgres_query works only with PostgreSQL databases.
Clean up
-
On your dev computer, remove the MCP server from the project configuration:
claude mcp remove teleport-databases -s project -
Delete both beams and the phase:
tsh beams ls tsh beams rm <database-beam> tsh beams rm <agent-beam> tsh phase rm beams-postgres -
Remove the roles from your user, then delete them:
me=$(tsh status --format=json | jq -r .active.username) roles=$(tctl get "users/$me" --format=json | jq -r '[.[0].spec.roles[] | select(. != "postgres-demo-host" and . != "read-only-demo-postgres")] | join(",")') tctl users update "$me" --set-roles="$roles" tctl rm roles/postgres-demo-host tctl rm roles/read-only-demo-postgres
The database disappears from tsh db ls shortly after its beam is deleted. Its join token expires an hour after the beam does. To delete it sooner:
tctl get tokens --format=json | jq -r '.[].metadata.name | select(startswith("beams-postgres-"))'
tctl rm token/TOKEN_NAMETroubleshoot
- Only
teleport_list_databasesappears, or it lists no databases. The URIs passed totsh mcp db startare wrong. Regenerate them withtsh mcp db config.teleport_list_databasesexplains what is missing. access to db denied. Your roles don’t allow that database, user or name. Check withtsh db connect --db-user=readonly --db-name=postgres beams-postgres.- The server doesn’t start, or tool calls fail after a while.
tsh mcp db startneeds a validtshsession when it starts. If the session expires while it runs, runtsh loginand retry the call. You don’t need to restart the MCP client. - The database doesn’t appear in
tsh db ls. Read the logs inside the database beam, for exampletsh beams exec <database-beam> -- beamctl logs database-setup.