Multi-Tenancy Support: Scoping MCP Queries to Tenant ID via RLS Session Variables #113
bruceHansen
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm integrating the Postgres MCP server into a multi-tenant Ruby on Rails application, where each LLM/agent query (via tools like execute_sql) needs to be automatically scoped to a specific company's company_id (UUID) for security and isolation. This is to enable safe, agent-driven database interactions without exposing tenant-specific data across boundaries.
Quick Background
Use Case: Rails app with shared Postgres DB, tables like users and orders have a company_id column. Queries come from a chat agent that calls MCP remotely.
Current Limitation: execute_sql takes raw SQL, so without modifications, agents could generate unscoped queries.
My Approach:
Enable Row-Level Security (RLS) on tables with a policy like:
This auto-filters queries without changing SQL.
Fork/modify
execute_sqlto accept an optional tenant_id param (validated UUID), then inject SET LOCAL app.current_tenant = '{tenant_id}' before executing the SQL (and reset after). Keeps it transaction-local to avoid leakage.Proposed diff (in the tool function):
This adds the param to the tool schema for agents to use.
From Rails/agent: Pass tenant_id from current_company.id.
Questions
Beta Was this translation helpful? Give feedback.
All reactions