Skip to content
Draft
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
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,4 @@ ENV PORT=3000

# server.js is created by next build from the standalone output
# https://nextjs.org/docs/pages/api-reference/next-config-js/output
CMD HOSTNAME="0.0.0.0" node server.js
CMD HOSTNAME="0.0.0.0" node server.js
9 changes: 9 additions & 0 deletions app/(auth)/.well-known/oauth-authorization-server/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { oAuthDiscoveryMetadata } from "better-auth/plugins";

import auth from "../../../../auth";

export async function handler(req: Request) {
return await oAuthDiscoveryMetadata(auth)(req);
}

export { handler as GET, handler as OPTIONS };
9 changes: 9 additions & 0 deletions app/(auth)/.well-known/oauth-protected-resource/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { oAuthProtectedResourceMetadata } from "better-auth/plugins";

import auth from "../../../../auth";

export async function handler(req: Request) {
return await oAuthProtectedResourceMetadata(auth)(req);
}

export { handler as GET, handler as OPTIONS };
58 changes: 58 additions & 0 deletions app/api/[slug]/mcp/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { NextRequest } from "next/server";

import auth from "@/auth";
import { getRagieApiKeyAndPartition } from "@/lib/server/ragie";
import { RAGIE_API_BASE_URL } from "@/lib/server/settings";
import { requireMcpAuthContext } from "@/lib/server/utils";

const handler = async (req: NextRequest, { params }: { params: Promise<{ slug: string }> }) => {
const session = await auth.api.getMcpSession({
headers: req.headers,
});
if (!session) {
return new Response(null, {
status: 401,
});
}
const { slug } = await params;

const { profile, tenant } = await requireMcpAuthContext(slug);
const { apiKey, partition } = await getRagieApiKeyAndPartition(tenant.id);

// Proxy the request to the Ragie MCP server
const localRagieMcpUrl = `${RAGIE_API_BASE_URL}/mcp/${partition}/`;

try {
const response = await fetch(localRagieMcpUrl, {
method: req.method,
headers: {
...Object.fromEntries(req.headers.entries()),
Authorization: `Bearer ${apiKey}`,
"Content-Type": req.headers.get("content-type") || "application/json",
},
body: req.method !== "GET" && req.method !== "HEAD" ? await req.text() : undefined,
});

return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
} catch (error) {
console.error("Error proxying request to Ragie MCP server:", error);
return new Response(
JSON.stringify({
error: "Failed to proxy request to Ragie MCP server",
message: error instanceof Error ? error.message : "Unknown error",
}),
{
status: 500,
headers: {
"Content-Type": "application/json",
},
},
);
}
};

export { handler as GET, handler as POST, handler as DELETE, handler as OPTIONS };
11 changes: 11 additions & 0 deletions app/api/auth/[...all]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,14 @@ import { toNextJsHandler } from "better-auth/next-js";
import auth from "@/auth";

export const { POST, GET } = toNextJsHandler(auth);

export async function OPTIONS() {
return new Response(null, {
status: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
},
});
}
6 changes: 5 additions & 1 deletion auth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { nextCookies } from "better-auth/next-js";
import { anonymous } from "better-auth/plugins";
import { anonymous, mcp } from "better-auth/plugins";

import db from "@/lib/server/db";
import * as schema from "@/lib/server/db/schema";
Expand All @@ -20,6 +20,7 @@ if (settings.AUTH_GOOGLE_ID && settings.AUTH_GOOGLE_SECRET) {
}

export const auth = betterAuth({
baseURL: settings.BETTER_AUTH_URL,
database: drizzleAdapter(db, {
provider: "pg",
schema,
Expand Down Expand Up @@ -54,6 +55,9 @@ export const auth = betterAuth({
await linkUsers(anonymousUser.user.id, newUser.user.id);
},
}),
mcp({
loginPage: "/sign-in",
}),
nextCookies(), // This must be the last plugin
],
});
Expand Down
70 changes: 70 additions & 0 deletions drizzle/0048_black_kat_farrell.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
CREATE TABLE IF NOT EXISTS "oauth_access_tokens" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
"access_token" text NOT NULL,
"refresh_token" text,
"access_token_expires_at" timestamp with time zone NOT NULL,
"refresh_token_expires_at" timestamp with time zone,
"client_id" text NOT NULL,
"user_id" uuid NOT NULL,
"scopes" text
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "oauth_applications" (
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
"id" uuid DEFAULT gen_random_uuid() NOT NULL,
"client_id" text NOT NULL,
"client_secret" text,
"name" text NOT NULL,
"redirect_urls" text,
"metadata" text,
"type" text NOT NULL,
"disabled" boolean DEFAULT false NOT NULL,
"user_id" uuid,
CONSTRAINT "oauth_applications_id_client_id_pk" PRIMARY KEY("id","client_id"),
CONSTRAINT "oauth_applications_client_id_unique" UNIQUE("client_id")
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "oauth_consents" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
"user_id" uuid NOT NULL,
"client_id" text NOT NULL,
"scopes" text,
"consent_given" boolean DEFAULT false NOT NULL
);
--> statement-breakpoint
ALTER TABLE "messages" ALTER COLUMN "model" SET DEFAULT 'claude-sonnet-4-5-20250929';--> statement-breakpoint
ALTER TABLE "tenants" ALTER COLUMN "default_model" SET DEFAULT 'claude-sonnet-4-5-20250929';--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "oauth_access_tokens" ADD CONSTRAINT "oauth_access_tokens_client_id_oauth_applications_client_id_fk" FOREIGN KEY ("client_id") REFERENCES "public"."oauth_applications"("client_id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "oauth_access_tokens" ADD CONSTRAINT "oauth_access_tokens_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "oauth_applications" ADD CONSTRAINT "oauth_applications_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "oauth_consents" ADD CONSTRAINT "oauth_consents_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "oauth_consents" ADD CONSTRAINT "oauth_consents_client_id_oauth_applications_client_id_fk" FOREIGN KEY ("client_id") REFERENCES "public"."oauth_applications"("client_id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
Loading