Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

feat(api): get_current_user tells an MCP client whose key it holds (#576)

Pasqual Troncone1c8610530b8a
diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md
index 0bca5525..e5f59d9f 100644
--- a/apps/api/AGENTS.md
+++ b/apps/api/AGENTS.md
@@ -105,7 +105,9 @@ Enforced declaratively through macros, never imperative calls in handlers.
- **Session:** `authContext` (named plugin) reads the better-auth session once, puts
`user` on context, throws 401 with none. `planner.ts` gates every planner route;
a feature also `.use(authContext)` when its handlers/macros reference `user`. An
- `x-api-key` header resolves through `getSession` — no special-casing.
+ `x-api-key` header resolves through `getSession` — no special-casing. A route outside
+ the planner that answers without credentials (`/me`) reads the same account through
+ `requestUser`, which also takes the MCP OAuth token of a tool call.
- **Membership:** access is by a `project_member` row (`owner` | `member`), raised by
the caller's role in the workspace that holds the project. Owners bypass the
permission matrix; the global `user.role` (`god` | `user`) does **not**. Keep at least
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index 0812b7f7..4052ea63 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -1,6 +1,5 @@
import {
auth,
- getSessionFromHeaders,
oauthAuthorizationServerMetadata,
oauthProtectedResourceMetadata,
openIdConfiguration,
@@ -10,7 +9,6 @@ import {
hasConfiguredGoogle,
hasConfiguredOidc,
getOidcLabel,
- isAccountDeactivated,
} from '@repo/auth';
import { db, hasConfiguredEmailProvider, user } from '@repo/db';
import { cors } from '@elysiajs/cors';
@@ -21,6 +19,7 @@ import { mountMcp } from './mcp/mount';
import { setMcpApp } from './mcp/app-ref';
import { gitWebhookRoutes } from './modules/git/webhook';
import { scimRoutes } from './modules/scim';
+import { currentUserRoutes } from './modules/current-user';
import { syncOidcGroupsAfterCallback } from './modules/scim/oidc-sync';
import { normalizeOpenApiResponse } from './openapi';
import pkg from '../../../package.json';
@@ -263,31 +262,7 @@ export const app = new Elysia()
if (url.pathname === OIDC_CALLBACK) await syncOidcGroupsAfterCallback(response);
return response;
})
- // Example protected handler: read the session from better-auth.
- .get(
- '/me',
- async ({ request }) => {
- const session = await getSessionFromHeaders(request.headers);
- // A deactivated account is not signed in as far as the app is concerned:
- // every planner route answers 401 for it, and this is what the screens ask
- // first. Deactivation arrives over SCIM or from god mode, after the session
- // was opened.
- if (!session || isAccountDeactivated(session.user)) {
- return { authenticated: false };
- }
- return { authenticated: true, user: session.user };
- },
- {
- detail: {
- tags: ['System'],
- summary: 'Get the current session user',
- description:
- 'Resolve the request credentials to a session and return the user it belongs to. ' +
- 'Without a session, or for a deactivated account, it answers ' +
- '`{ authenticated: false }` instead of failing.',
- },
- },
- )
+ .use(currentUserRoutes)
// What the sign-in and sign-up screens need before there is a session: whether
// registration is open, invite-only, or closed, and which sign-in methods are
// offered. Public on purpose — the screens are reached logged out. It carries no
@@ -346,7 +321,7 @@ export const app = new Elysia()
// MCP endpoint (POST /mcp). Added after the chain so `type App` (the Eden client
// type) stays the REST surface; the MCP endpoint is JSON-RPC, not called via Eden.
-// Its tools are generated from the planner routes tagged with mcpTool().
+// Its tools are generated from the routes tagged with mcpTool().
mountMcp(app);
// Hands the assembled app to the internal agent runtime, which builds an agent's
diff --git a/apps/api/src/mcp/instructions.ts b/apps/api/src/mcp/instructions.ts
index d504a9ea..9180e4b5 100644
--- a/apps/api/src/mcp/instructions.ts
+++ b/apps/api/src/mcp/instructions.ts
@@ -33,6 +33,11 @@ checklists and their items.
search_issues and list_issues are for finding issues by text or by field, not for
resolving an identifier.
+## You
+
+Your key acts as one user. When a request says "me", "my" or "mine", call
+get_current_user for that user's id rather than matching a name or an email.
+
## Teams
A team owns the projects, the AI agents, the skills and the configured tools. It is
diff --git a/apps/api/src/modules/current-user/__tests__/integration/current-user.test.ts b/apps/api/src/modules/current-user/__tests__/integration/current-user.test.ts
new file mode 100644
index 00000000..c3aec160
--- /dev/null
+++ b/apps/api/src/modules/current-user/__tests__/integration/current-user.test.ts
@@ -0,0 +1,114 @@
+import { beforeEach, describe, expect, it } from 'bun:test';
+import { auth } from '@repo/auth';
+import { app, authedApi } from '#tests/helpers/app';
+import { resetDb } from '#tests/helpers/db';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { createAgent, teamOf } from '#tests/helpers/agents';
+import { mcpAccessToken } from '#tests/helpers/mcp';
+import { getAgentById, getInternalAgentApiKey } from '#modules/agents/core/service';
+
+// An MCP client acts as the person behind its key, and "my issues" needs to know who
+// that is. Without a tool that says so, the model guessed from the client's own context
+// and answered for someone else.
+
+async function rpc(apiKey: string, method: string, params: Record<string, unknown> = {}) {
+ const res = await app.handle(
+ new Request('http://localhost/mcp', {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${apiKey}`,
+ 'content-type': 'application/json',
+ accept: 'application/json, text/event-stream',
+ },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
+ }),
+ );
+ const text = await res.text();
+ return JSON.parse(text.slice(text.indexOf('data: ') + 6)).result;
+}
+
+async function currentUser(apiKey: string) {
+ const result = await rpc(apiKey, 'tools/call', { name: 'get_current_user', arguments: {} });
+ return { data: JSON.parse(result.content[0].text), isError: result.isError === true };
+}
+
+describe('GET /me', () => {
+ beforeEach(resetDb);
+
+ it('keeps every field of the stored user and adds the zone and whether it is an agent', async () => {
+ const person = await signUpTestUser({ name: 'Person', email: '[email protected]' });
+ const asPerson = authedApi(person.cookie);
+ await asPerson.account.preferences.patch({ timezone: 'Europe/Madrid' });
+ const session = await auth.api.getSession({ headers: new Headers({ cookie: person.cookie }) });
+
+ const { data, status } = await asPerson.me.get();
+
+ expect(status).toBe(200);
+ // Treaty revives the iso() dates into Dates, so they compare with the session's own.
+ expect(data as unknown).toEqual({
+ authenticated: true,
+ user: { ...session!.user, timezone: 'Europe/Madrid', isAgent: false },
+ });
+ expect(data).toMatchObject({ user: { id: person.userId, username: 'person.one' } });
+ });
+
+ it('tells an MCP client whose key it holds', async () => {
+ const owner = await signUpTestUser({ name: 'Owner' });
+ await signUpTestUser({ name: 'Someone Else' });
+ const { key } = await auth.api.createApiKey({ body: { userId: owner.userId, name: 'mcp' } });
+
+ const { data, isError } = await currentUser(key);
+
+ expect(isError).toBe(false);
+ expect(data).toMatchObject({
+ authenticated: true,
+ user: { id: owner.userId, name: 'Owner', timezone: 'UTC', isAgent: false },
+ });
+ });
+
+ it('tells a client signed in over OAuth who approved it', async () => {
+ await signUpTestUser();
+ const person = await signUpTestUser({ name: 'Person' });
+
+ const { data, isError } = await currentUser(await mcpAccessToken(person.cookie));
+
+ expect(isError).toBe(false);
+ expect(data).toMatchObject({
+ authenticated: true,
+ user: { id: person.userId, name: 'Person', isAgent: false },
+ });
+ });
+
+ it('tells an agent it is one, with its handle', async () => {
+ const owner = await signUpTestUser({ name: 'Owner' });
+ const asOwner = authedApi(owner.cookie);
+ await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });
+ const teamId = await teamOf(asOwner, 'MKT');
+ const created = await createAgent(asOwner, 'MKT', {
+ name: 'Triage Bot',
+ username: 'triage',
+ kind: 'internal',
+ });
+ const agent = await getAgentById(created.data!.agent.id, teamId);
+
+ const { data } = await currentUser(await getInternalAgentApiKey(agent!));
+
+ expect(data).toMatchObject({
+ authenticated: true,
+ user: { id: created.data!.agent.userId, username: 'triage', isAgent: true },
+ });
+ });
+
+ it('points the model at it for "me" in the server instructions', async () => {
+ const owner = await signUpTestUser();
+ const { key } = await auth.api.createApiKey({ body: { userId: owner.userId, name: 'mcp' } });
+
+ const { instructions } = await rpc(key, 'initialize', {
+ protocolVersion: '2025-06-18',
+ capabilities: {},
+ clientInfo: { name: 'test', version: '0' },
+ });
+
+ expect(instructions).toContain('get_current_user');
+ });
+});
diff --git a/apps/api/src/modules/current-user/index.ts b/apps/api/src/modules/current-user/index.ts
new file mode 100644
index 00000000..61dfad3d
--- /dev/null
+++ b/apps/api/src/modules/current-user/index.ts
@@ -0,0 +1,36 @@
+import { Elysia } from 'elysia';
+import { isAccountDeactivated } from '@repo/auth';
+import { requestUser } from '#shared/auth-context';
+import { mcpTool } from '#mcp/generate';
+import { Me } from './model';
+import { getCurrentUser } from './service';
+
+// Mounted on the root app, not under the planner: without credentials it answers
+// `{ authenticated: false }`, where the planner's authContext would answer 401.
+export const currentUserRoutes = new Elysia({
+ name: 'current-user',
+ detail: { tags: ['System'] },
+}).get(
+ '/me',
+ async ({ request }) => {
+ const account = await requestUser(request);
+ // A deactivated account is not signed in as far as the app is concerned: every
+ // planner route answers 401 for it. Deactivation arrives over SCIM or from god
+ // mode, after the session was opened.
+ if (!account || isAccountDeactivated(account)) return { authenticated: false as const };
+ return { authenticated: true as const, user: await getCurrentUser(account) };
+ },
+ {
+ response: { 200: Me },
+ detail: {
+ summary: 'Get the current user',
+ description:
+ 'Who you are: the user your key, sign-in or MCP connection acts as. Call it when a ' +
+ 'request says "me", "my" or "mine" — user.id is the assigneeUserId of your own ' +
+ 'issues — instead of guessing from a name or an email. user.timezone is the zone ' +
+ 'to read "today" or "this week" in. Without credentials, or for a deactivated ' +
+ 'account, it answers `{ authenticated: false }` instead of failing.',
+ ...mcpTool('get_current_user'),
+ },
+ },
+);
diff --git a/apps/api/src/modules/current-user/model.ts b/apps/api/src/modules/current-user/model.ts
new file mode 100644
index 00000000..cd060e16
--- /dev/null
+++ b/apps/api/src/modules/current-user/model.ts
@@ -0,0 +1,26 @@
+import { t } from 'elysia';
+
+// Every field of the stored user is declared: the response drops any field the schema
+// leaves out.
+export const CurrentUser = t.Object({
+ id: t.String(),
+ name: t.String(),
+ email: t.String(),
+ emailVerified: t.Boolean(),
+ image: t.Nullable(t.String()),
+ createdAt: t.String(),
+ updatedAt: t.String(),
+ // An agent's handle lives on its agent row; this carries it, as the member list does.
+ username: t.Nullable(t.String()),
+ displayUsername: t.Nullable(t.String()),
+ role: t.Nullable(t.String()),
+ active: t.Nullable(t.Boolean()),
+ // The IANA zone the person reads dates in, so "today" or "this week" can be told.
+ timezone: t.String(),
+ isAgent: t.Boolean(),
+});
+
+export const Me = t.Union([
+ t.Object({ authenticated: t.Literal(false) }),
+ t.Object({ authenticated: t.Literal(true), user: CurrentUser }),
+]);
diff --git a/apps/api/src/modules/current-user/service.ts b/apps/api/src/modules/current-user/service.ts
new file mode 100644
index 00000000..723e1b64
--- /dev/null
+++ b/apps/api/src/modules/current-user/service.ts
@@ -0,0 +1,34 @@
+import { eq } from 'drizzle-orm';
+import { aiAgent, db, user, userPreference } from '@repo/db';
+import { iso } from '#shared/lib';
+import type { SessionUser } from '#shared/auth-context';
+import { DEFAULT_TIMEZONE } from '#modules/user-preferences/service';
+
+export async function getCurrentUser(account: SessionUser) {
+ const [row] = await db
+ .select({
+ agentId: aiAgent.id,
+ agentUsername: aiAgent.username,
+ timezone: userPreference.timezone,
+ })
+ .from(user)
+ .leftJoin(aiAgent, eq(aiAgent.userId, user.id))
+ .leftJoin(userPreference, eq(userPreference.userId, user.id))
+ .where(eq(user.id, account.id))
+ .limit(1);
+ return {
+ id: account.id,
+ name: account.name,
+ email: account.email,
+ emailVerified: account.emailVerified,
+ image: account.image ?? null,
+ createdAt: iso(account.createdAt),
+ updatedAt: iso(account.updatedAt),
+ username: account.username ?? row?.agentUsername ?? null,
+ displayUsername: account.displayUsername ?? null,
+ role: account.role ?? null,
+ active: account.active ?? null,
+ timezone: row?.timezone ?? DEFAULT_TIMEZONE,
+ isAgent: Boolean(row?.agentId),
+ };
+}
diff --git a/apps/api/src/shared/auth-context.ts b/apps/api/src/shared/auth-context.ts
index 41aa2d5b..f00edcc2 100644
--- a/apps/api/src/shared/auth-context.ts
+++ b/apps/api/src/shared/auth-context.ts
@@ -42,20 +42,27 @@ export type SessionUser = SessionResult['user'];
export const authContext = new Elysia({ name: 'auth-context' }).resolve(
{ as: 'scoped' },
async ({ request, path }): Promise<{ user: SessionUser | null }> => {
- const session = await getSessionFromHeaders(request.headers);
- if (session) return { user: await signedIn(session.user) };
- const mcpToken = getMcpOAuthToken(request);
- const mcpUserId = mcpToken ? await verifyMcpAccessToken(mcpToken) : null;
- if (mcpUserId) {
- const user = await db.query.user.findFirst({ where: eq(users.id, mcpUserId) });
- if (user) return { user: await signedIn(user as SessionUser) };
- }
+ const user = await requestUser(request);
+ if (user) return { user: await signedIn(user) };
// The public raw-attachment route has no session and needs none.
if (request.method === 'GET' && PUBLIC_GET.test(path)) return { user: null };
throw new HttpError(401, 'Authentication required');
},
);
+// The account the request's credentials belong to: a session or an API key, or the MCP
+// OAuth token of a tool call, which reaches the route beside the request rather than in
+// its headers. Whether the account may act is left to the caller.
+export async function requestUser(request: Request): Promise<SessionUser | null> {
+ const session = await getSessionFromHeaders(request.headers);
+ if (session) return session.user;
+ const mcpToken = getMcpOAuthToken(request);
+ const mcpUserId = mcpToken ? await verifyMcpAccessToken(mcpToken) : null;
+ if (!mcpUserId) return null;
+ const user = await db.query.user.findFirst({ where: eq(users.id, mcpUserId) });
+ return (user as SessionUser | undefined) ?? null;
+}
+
// A deactivated account goes no further. Any other gets its personal workspace here when
// it has none yet, so one made before personal workspaces, by SCIM or while they were off
// has it on its next request instead of its next sign-in.