Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(mcp): connect GitHub once through the Macro account link (#9116)

Eric Hayese77f598c96b1
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 5ba00ff896..21e895b9ec 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -10377,9 +10377,11 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
"crates/cowlike",
+ "crates/document_sub_type",
"crates/genai_telemetry",
"crates/harness_id",
"crates/harness_token",
@@ -10390,10 +10392,15 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mcp_client",
+ "crates/model",
"crates/model-entity",
"crates/model-error-response",
"crates/model_file_type",
+ "crates/model_owner",
"crates/model_user",
+ "crates/models_bulk_upload",
+ "crates/models_pagination",
+ "crates/models_permissions",
"crates/non_empty",
"crates/prompt",
"crates/remote_env_var",
@@ -10404,9 +10411,11 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
"crates/cowlike",
+ "crates/document_sub_type",
"crates/genai_telemetry",
"crates/harness_id",
"crates/harness_token",
@@ -10419,10 +10428,15 @@
"crates/mcp_client",
"crates/mcp_select",
"crates/mcp_toolset",
+ "crates/model",
"crates/model-entity",
"crates/model-error-response",
"crates/model_file_type",
+ "crates/model_owner",
"crates/model_user",
+ "crates/models_bulk_upload",
+ "crates/models_pagination",
+ "crates/models_permissions",
"crates/non_empty",
"crates/pipedream_mcp",
"crates/prompt",
@@ -11373,9 +11387,11 @@
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
"crates/cowlike",
+ "crates/document_sub_type",
"crates/genai_telemetry",
"crates/generic_email_domains",
"crates/harness_id",
@@ -11387,10 +11403,15 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mcp_client",
+ "crates/model",
"crates/model-entity",
"crates/model-error-response",
"crates/model_file_type",
+ "crates/model_owner",
"crates/model_user",
+ "crates/models_bulk_upload",
+ "crates/models_pagination",
+ "crates/models_permissions",
"crates/non_empty",
"crates/onboarding",
"crates/prompt",
diff --git a/Cargo.lock b/Cargo.lock
index 0cac25d950..91b38e89e4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6613,6 +6613,7 @@ dependencies = [
"macro_tower_layers",
"macro_user_id",
"macro_uuid",
+ "mcp_client",
"messages",
"mockall",
"model",
@@ -12705,6 +12706,7 @@ dependencies = [
"anyhow",
"async-openai",
"async-trait",
+ "authentication_service_client",
"axum",
"base64 0.22.1",
"futures",
diff --git a/apps/web/src/features/connector-import/core/catalog.ts b/apps/web/src/features/connector-import/core/catalog.ts
index 24c66eb1ce..2c0cf088ec 100644
--- a/apps/web/src/features/connector-import/core/catalog.ts
+++ b/apps/web/src/features/connector-import/core/catalog.ts
@@ -112,8 +112,7 @@ export const IMPORT_CATEGORIES: Record<ImportCategory, ImportCategoryConfig> = {
name: 'GitHub',
detail: 'Issues',
icon: IconGithub as ImportIcon,
- // Macro's GitHub preset in `QUICK_CONNECT_SERVERS`.
- mcpUrl: 'https://api.githubcopilot.com/mcp',
+ // Connects through the GitHub account link (an overlaid app).
},
{
appSlug: 'trello',
diff --git a/apps/web/src/features/connector-import/views/import-dialog.test.tsx b/apps/web/src/features/connector-import/views/import-dialog.test.tsx
index 18855d49dd..f7c0e7dc4c 100644
--- a/apps/web/src/features/connector-import/views/import-dialog.test.tsx
+++ b/apps/web/src/features/connector-import/views/import-dialog.test.tsx
@@ -125,16 +125,12 @@ describe('connector import dialog', () => {
);
});
- it('connects GitHub through its native MCP server, not Pipedream', async () => {
+ it('connects GitHub as an overlaid app, without its own MCP authorization', async () => {
const fake = setup('tasks');
fake.setConnectOutcome('started');
fireEvent.click(screen.getByRole('button', { name: 'Connect GitHub' }));
expect(fake.context.connect).toHaveBeenCalledWith(
- {
- appSlug: 'github',
- name: 'GitHub',
- mcpUrl: 'https://api.githubcopilot.com/mcp',
- },
+ { appSlug: 'github', name: 'GitHub', mcpUrl: undefined },
expect.anything()
);
// Authorization finishes in another tab; the row waits for the result.
diff --git a/apps/web/src/features/settings/connections/PipedreamAiProvider.tsx b/apps/web/src/features/settings/connections/PipedreamAiProvider.tsx
index b37c37cbeb..67ca156d50 100644
--- a/apps/web/src/features/settings/connections/PipedreamAiProvider.tsx
+++ b/apps/web/src/features/settings/connections/PipedreamAiProvider.tsx
@@ -1,7 +1,9 @@
+import { linkGithubAccount } from '@core/auth/authorize-github';
import { toast } from '@core/component/Toast/Toast';
import { createPipedreamCatalogConnect } from '@core/pipedream/catalog';
import { connectSlugForPipedreamApp } from '@core/pipedream/slugs';
import { fireAndForget } from '@core/util/fireAndForget';
+import { useDeleteGithubLinkMutation } from '@queries/auth';
import {
useDeletePipedreamConnectionMutation,
useUpdatePipedreamConnectionMutation,
@@ -99,6 +101,9 @@ export function PipedreamAiProvider(props: {
const update = useUpdatePipedreamConnectionMutation();
const remove = useDeletePipedreamConnectionMutation();
const native = useNativeMcpActions();
+ // The GitHub account link authorizes GitHub's MCP server.
+ const unlinkGithub = useDeleteGithubLinkMutation();
+ const linksGithub = () => props.provider === 'github';
const { connect, busy } = createPipedreamCatalogConnect({
entry: () => ({
app_slug: connectSlugForPipedreamApp(props.provider),
@@ -135,6 +140,22 @@ export function PipedreamAiProvider(props: {
if (cap.mechanism === 'native-mcp') {
const url = cap.sourceUrl;
if (!url) return;
+ if (linksGithub()) {
+ setDisconnect({
+ title: 'Disconnect from Macro',
+ body: 'Disconnect GitHub? This unlinks your GitHub account from Macro, which pull request features also use.',
+ onConfirm: () =>
+ unlinkGithub.mutate(undefined, {
+ onSuccess: () => {
+ // Any GitHub server added before the link went with it.
+ native.remove.mutate({ url });
+ toast.success('Disconnected GitHub from Macro');
+ },
+ onError: () => toast.failure('Failed to disconnect'),
+ }),
+ });
+ return;
+ }
setDisconnect({
title: 'Disconnect from Macro',
body: `Disconnect ${copy.name}?`,
@@ -168,6 +189,13 @@ export function PipedreamAiProvider(props: {
const reconnect = () => {
const cap = row();
if (!cap) return;
+ if (linksGithub()) {
+ fireAndForget(
+ linkGithubAccount('Failed to connect GitHub'),
+ 'connections-settings'
+ );
+ return;
+ }
if (cap.mechanism === 'native-mcp') {
const url = cap.sourceUrl;
if (!url) return;
@@ -188,7 +216,9 @@ export function PipedreamAiProvider(props: {
connectBusy={busy()}
authPending={native.authorize.isPending}
updatePending={native.update.isPending || update.isPending}
- removePending={native.remove.isPending || remove.isPending}
+ removePending={
+ native.remove.isPending || remove.isPending || unlinkGithub.isPending
+ }
/>
);
diff --git a/apps/web/src/lib/core/auth/authorize-github.ts b/apps/web/src/lib/core/auth/authorize-github.ts
index 2cbab81567..eb199d93f3 100644
--- a/apps/web/src/lib/core/auth/authorize-github.ts
+++ b/apps/web/src/lib/core/auth/authorize-github.ts
@@ -7,7 +7,10 @@ import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { fireAndForget } from '@core/util/fireAndForget';
import { isDesktopPlatform } from '@core/util/platform';
import { Telemetry } from '@macro-inc/observability';
-import { invalidateGithubLinkStatus } from '@queries/auth';
+import {
+ githubLinkAuthorizationUrl,
+ invalidateGithubLinkStatus,
+} from '@queries/auth';
/**
* Where GitHub consent started from the desktop app returns. The system
@@ -70,3 +73,14 @@ export function handleGithubLinkCallback(path: string): boolean {
fireAndForget(invalidateGithubLinkStatus(), 'github-link');
return true;
}
+
+/**
+ * Link the user's GitHub account, or relink one whose token stopped working.
+ * The link also authorizes GitHub for Macro AI. Resolves as
+ * {@link authorizeGithub} does.
+ */
+export async function linkGithubAccount(
+ failureMessage: string
+): Promise<boolean> {
+ return await authorizeGithub(githubLinkAuthorizationUrl, failureMessage);
+}
diff --git a/apps/web/src/lib/queries/auth/github-link.ts b/apps/web/src/lib/queries/auth/github-link.ts
index 01886a20eb..ea6615316f 100644
--- a/apps/web/src/lib/queries/auth/github-link.ts
+++ b/apps/web/src/lib/queries/auth/github-link.ts
@@ -101,6 +101,14 @@ export async function invalidateGithubLinkStatus() {
return queryClient.prefetchQuery({ ...options, staleTime: 0 });
}
+/**
+ * The GitHub authorization URL that links the user's account, or relinks one
+ * whose token stopped working; the callback returns to `originalUrl`.
+ */
+export async function githubLinkAuthorizationUrl(originalUrl: string) {
+ return await throwOnErr(() => authServiceClient.initGithubLink(originalUrl));
+}
+
export function useInitGithubLinkMutation() {
return useMutation(() => ({
mutationFn: async (originalUrl?: string) =>
diff --git a/apps/web/src/lib/queries/auth/index.ts b/apps/web/src/lib/queries/auth/index.ts
index 92624c16ff..dd9b3dfea5 100644
--- a/apps/web/src/lib/queries/auth/index.ts
+++ b/apps/web/src/lib/queries/auth/index.ts
@@ -20,6 +20,7 @@ export {
export {
type GithubLink,
type GithubLinkStatus,
+ githubLinkAuthorizationUrl,
invalidateGithubLinkStatus,
useDeleteGithubLinkMutation,
useGithubLinkStatusQuery,
diff --git a/apps/web/src/lib/queries/pipedream-connectors.test.ts b/apps/web/src/lib/queries/pipedream-connectors.test.ts
index bffc992a84..2822b7efdd 100644
--- a/apps/web/src/lib/queries/pipedream-connectors.test.ts
+++ b/apps/web/src/lib/queries/pipedream-connectors.test.ts
@@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => ({
fetchServers: vi.fn(),
reservePopup: vi.fn(),
assignUrl: vi.fn(),
+ linkGithub: vi.fn(),
overlays: [] as { app_slug: string; server_url: string }[],
overlaysUnavailable: false,
cachedOverlays: undefined as
@@ -24,6 +25,9 @@ const mocks = vi.hoisted(() => ({
| undefined,
}));
vi.mock('@core/util/platform', () => ({ isTauri: () => mocks.native }));
+vi.mock('@core/auth/authorize-github', () => ({
+ linkGithubAccount: mocks.linkGithub,
+}));
vi.mock('@core/pipedream/connect-native', () => ({
openNativePipedreamConnectUI: mocks.openNative,
}));
@@ -262,6 +266,35 @@ describe('overlaid apps connect through their own MCP server', () => {
});
});
+describe('GitHub connects through the account link', () => {
+ const github = {
+ app_slug: 'github',
+ server_url: 'https://api.githubcopilot.com/mcp',
+ };
+
+ beforeEach(() => {
+ mocks.cachedOverlays = [github];
+ });
+
+ it('links the account instead of authorizing the server or Pipedream', async () => {
+ mocks.linkGithub.mockResolvedValue(true);
+
+ expect(await connectPipedreamApp({ appSlug: 'github' })).toBe('connected');
+ expect(mocks.linkGithub).toHaveBeenCalled();
+ expect(mocks.reservePopup).not.toHaveBeenCalled();
+ expect(mocks.startAuth).not.toHaveBeenCalled();
+ expect(mocks.token).not.toHaveBeenCalled();
+ expect(mocks.invalidate).toHaveBeenCalled();
+ });
+
+ it('reports closed when the page leaves for GitHub or the link fails', async () => {
+ mocks.linkGithub.mockResolvedValue(false);
+
+ expect(await connectPipedreamApp({ appSlug: 'github' })).toBe('closed');
+ expect(mocks.startAuth).not.toHaveBeenCalled();
+ });
+});
+
describe('a backend without overlays', () => {
it('connects through Pipedream when the overlay list cannot be read', async () => {
mocks.overlaysUnavailable = true;
diff --git a/apps/web/src/lib/queries/pipedream-connectors.ts b/apps/web/src/lib/queries/pipedream-connectors.ts
index c673e2e83d..b503ef3a45 100644
--- a/apps/web/src/lib/queries/pipedream-connectors.ts
+++ b/apps/web/src/lib/queries/pipedream-connectors.ts
@@ -1,3 +1,4 @@
+import { linkGithubAccount } from '@core/auth/authorize-github';
import {
openPipedreamConnectUI,
type PipedreamConnectEvent,
@@ -300,6 +301,8 @@ let pipedreamUnsupported = false;
* An overlaid app (see {@link usePipedreamOverlaysQuery}) never goes through
* Pipedream: it authorizes its own MCP server with the native MCP OAuth flow
* in a new tab instead, and is connected once that server is authorized.
+ * GitHub's server is authorized by the Macro GitHub account link, so GitHub
+ * links the account instead.
*
* Resolves `'connected'` on success (connections cache already refreshed),
* `'closed'` when the user dismissed the UI without finishing, and
@@ -320,7 +323,8 @@ export async function connectPipedreamApp(args: {
const cachedOverlay = queryClient
.getQueryData<PipedreamOverlayResponse[]>(KEYS.overlays)
?.find((overlay) => overlay.app_slug === args.appSlug);
- const popup = cachedOverlay ? reserveOauthPopup() : null;
+ const popup =
+ cachedOverlay && !linksGithub(cachedOverlay) ? reserveOauthPopup() : null;
return Telemetry.span('pipedream.connect', async (span) => {
span.setAttr('connector.app_slug', args.appSlug);
span.setAttr('connector.native', isTauri());
@@ -328,9 +332,11 @@ export async function connectPipedreamApp(args: {
const overlay =
cachedOverlay ?? (await lookUpOverlay(args.appSlug, span));
span.setAttr('connector.overlaid', overlay !== undefined);
- const outcome = overlay
- ? await connectOverlaidApp(overlay, args, popup, span)
- : await connectPipedreamAccount(args, span);
+ const outcome = !overlay
+ ? await connectPipedreamAccount(args, span)
+ : linksGithub(overlay)
+ ? await connectGithubLink(span)
+ : await connectOverlaidApp(overlay, args, popup, span);
span.setAttr('connector.outcome', outcome);
return outcome;
} catch (error) {
@@ -362,6 +368,30 @@ async function lookUpOverlay(
return overlays.value.find((overlay) => overlay.app_slug === appSlug);
}
+const GITHUB_APP_SLUG = 'github';
+
+/** Whether `overlay` is GitHub, which the account link authorizes. */
+function linksGithub(overlay: PipedreamOverlayResponse) {
+ return overlay.app_slug === GITHUB_APP_SLUG;
+}
+
+/**
+ * Link the user's GitHub account, which the backend reads to authorize
+ * GitHub's MCP server. On the web the page leaves for GitHub and returns
+ * after the link, so this resolves `'closed'`; on native mobile it resolves
+ * once the link is made.
+ */
+async function connectGithubLink(span: Span): Promise<PipedreamConnectOutcome> {
+ const linked = await span.span('github.link', async () =>
+ linkGithubAccount('Failed to connect GitHub')
+ );
+ if (!linked) return 'closed';
+ await queryClient.invalidateQueries({
+ queryKey: mcpServersQueryOptions().queryKey,
+ });
+ return 'connected';
+}
+
const OVERLAY_AUTH_POLL_MS = 2000;
// Matches the backend's pending-authorization lifetime.
const OVERLAY_AUTH_TIMEOUT_MS = 10 * 60 * 1000;
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index 82e642921b..d2c102bf2f 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -170,7 +170,14 @@ pub fn build_cognition_tool_context() -> anyhow::Result<crate::ToolCognitionTool
/// `import_jobs` runs the context's Notion workspace imports; the host calls
/// [`crate::ImportJobs::hand_over`] on shutdown so they move to another
/// process instead of waiting for their leases to lapse.
-#[tracing::instrument(skip(pool, event_task_tracker, import_jobs, recorder), err)]
+///
+/// `linked_github` reads GitHub account-link tokens so GitHub's MCP server
+/// reads as connected for a linked user; `None` where the host cannot reach
+/// the authentication service.
+#[tracing::instrument(
+ skip(pool, event_task_tracker, import_jobs, recorder, linked_github),
+ err
+)]
pub async fn build_tool_service_context_from_env(
pool: sqlx::PgPool,
event_task_tracker: TaskTracker,
@@ -178,6 +185,7 @@ pub async fn build_tool_service_context_from_env(
enforcement: ai_usage::AiUsageEnforcement,
pricing: ai_billing::AiPricing,
recorder: Arc<dyn ai_usage::UsageRecorder>,
+ linked_github: Option<Arc<dyn mcp_client::domain::ports::LinkedGithubTokens>>,
) -> anyhow::Result<ToolServiceContext> {
let env = ToolContextEnvVars::new()?;
let maybe_env = ToolContextMaybeEnvVars::new();
@@ -578,12 +586,13 @@ pub async fn build_tool_service_context_from_env(
let mcp_encryption_key =
mcp_client::domain::models::AesKey::try_from(mcp_credentials_key.as_ref())
.context("invalid MCP credentials encryption key")?;
- Some(Arc::new(
+ Some(Arc::new(mcp_client::outbound::NativeServerStore::new(
mcp_client::outbound::pg_server_repo::PgServerRepo::new(
pool.clone(),
mcp_encryption_key,
),
- ))
+ linked_github,
+ )))
}
None => None,
};
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index 78f9a678a0..a9bc4523bc 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -308,7 +308,7 @@ fn tools_for_inner(host: AiHost, code_mode_direct: bool) -> ToolSetWithPrompt {
let toolset = match host {
AiHost::Chat | AiHost::AgentSession => {
toolset.add_subtoolset::<ToolMcpServerToolContext>(mcp_server_toolset::<
- mcp_client::outbound::pg_server_repo::PgServerRepo,
+ mcp_client::outbound::NativeServerStore,
>())
}
AiHost::ChannelBot | AiHost::Mcp => toolset,
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 1b43fc2e1c..1baa47a82e 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -1977,7 +1977,7 @@ pub type ToolPipedreamConnection =
/// server store and the Pipedream connection store. Picks which stack
/// serves a user's tools (Pipedream connectors win; see `mcp_select`).
pub type ToolMcpSelector = mcp_select::McpToolSelector<
- mcp_client::outbound::pg_server_repo::PgServerRepo,
+ mcp_client::outbound::NativeServerStore,
pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo,
ToolPipedreamConnection,
>;
@@ -1996,9 +1996,8 @@ pub type ToolImportService = import::domain::service::ImportServiceImpl<
/// The custom MCP server tools, wired by hosts holding the MCP credentials
/// key.
-pub type ToolMcpServerToolContext = mcp_client::inbound::toolset::McpServerToolContext<
- mcp_client::outbound::pg_server_repo::PgServerRepo,
->;
+pub type ToolMcpServerToolContext =
+ mcp_client::inbound::toolset::McpServerToolContext<mcp_client::outbound::NativeServerStore>;
/// Type alias for the import tool context, wired by hosts with connector access.
pub type ToolImportToolContext = import::inbound::toolset::ImportToolContext<ToolImportService>;
@@ -2125,7 +2124,7 @@ pub struct ToolServiceContext {
pub type ToolConnectorToolContext = pipedream_mcp::inbound::toolset::ConnectorToolContext<
pipedream_mcp::outbound::api::PipedreamClient,
pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo,
- mcp_select::NativeOverlayConnections<mcp_client::outbound::pg_server_repo::PgServerRepo>,
+ mcp_select::NativeOverlayConnections<mcp_client::outbound::NativeServerStore>,
>;
/// Wire connector discovery at the composition boundary.
@@ -2135,7 +2134,7 @@ pub type ToolConnectorToolContext = pipedream_mcp::inbound::toolset::ConnectorTo
pub fn build_connector_tool_context(
pool: sqlx::PgPool,
client: Option<Arc<pipedream_mcp::outbound::api::PipedreamClient>>,
- native_servers: Option<Arc<mcp_client::outbound::pg_server_repo::PgServerRepo>>,
+ native_servers: Option<Arc<mcp_client::outbound::NativeServerStore>>,
) -> ToolConnectorToolContext {
pipedream_mcp::inbound::toolset::ConnectorToolContext {
service: Arc::new(
diff --git a/crates/authentication_service_client/src/github_access_token.rs b/crates/authentication_service_client/src/github_access_token.rs
new file mode 100644
index 0000000000..8625092193
--- /dev/null
+++ b/crates/authentication_service_client/src/github_access_token.rs
@@ -0,0 +1,46 @@
+use crate::AuthServiceClient;
+use crate::error::{AuthServiceClientError, GenericErrorResponse};
+use model::authentication::github_token::GithubAccessToken;
+
+impl AuthServiceClient {
+ /// The user's GitHub token from their account link. `None` when they
+ /// never linked or the token no longer works; either way they have to
+ /// link GitHub before it can be used.
+ #[tracing::instrument(skip(self), err)]
+ pub async fn get_github_access_token(
+ &self,
+ macro_user_id: &str,
+ ) -> Result<Option<GithubAccessToken>, AuthServiceClientError> {
+ let res = self
+ .client
+ .get(format!("{}/internal/github_access_token", self.url))
+ .query(&[("macro_user_id", macro_user_id)])
+ .send()
+ .await
+ .map_err(|e| AuthServiceClientError::RequestBuildError {
+ details: e.to_string(),
+ })?;
+
+ match res.status() {
+ reqwest::StatusCode::OK => {
+ res.json::<GithubAccessToken>()
+ .await
+ .map(Some)
+ .map_err(|e| {
+ AuthServiceClientError::Generic(GenericErrorResponse {
+ message: e.to_string(),
+ })
+ })
+ }
+ reqwest::StatusCode::NOT_FOUND | reqwest::StatusCode::PRECONDITION_REQUIRED => Ok(None),
+ reqwest::StatusCode::UNAUTHORIZED => Err(AuthServiceClientError::Unauthorized),
+ reqwest::StatusCode::FORBIDDEN => Err(AuthServiceClientError::Forbidden),
+ status => {
+ let details = res.text().await.unwrap_or_default();
+ Err(AuthServiceClientError::InternalServerError {
+ details: format!("{status}: {details}"),
+ })
+ }
+ }
+ }
+}
diff --git a/crates/authentication_service_client/src/lib.rs b/crates/authentication_service_client/src/lib.rs
index 6a0c639c14..0cb51fd721 100644
--- a/crates/authentication_service_client/src/lib.rs
+++ b/crates/authentication_service_client/src/lib.rs
@@ -1,6 +1,7 @@
pub mod ai_billing;
pub mod delete_inbox_grant_user;
pub mod error;
+pub mod github_access_token;
pub mod google_access_token;
pub mod microsoft_access_token;
pub mod relocate_inbox_grant;
diff --git a/crates/github/src/domain/ports/link.rs b/crates/github/src/domain/ports/link.rs
index ccf77c2aac..a95bbe4452 100644
--- a/crates/github/src/domain/ports/link.rs
+++ b/crates/github/src/domain/ports/link.rs
@@ -258,6 +258,14 @@ pub trait GithubLinkService: Send + Sync + 'static {
user_id: &MacroUserId<Lowercase<'static>>,
) -> impl Future<Output = Result<GithubLinkStatus, GithubError>> + Send;
+ /// The user's GitHub token from their account link, checked against
+ /// GitHub. [`GithubError::NoLinkFound`] when they never linked,
+ /// [`GithubError::ReauthenticationRequired`] when the token no longer works.
+ fn get_user_access_token(
+ &self,
+ user_id: &MacroUserId<Lowercase<'static>>,
+ ) -> impl Future<Output = Result<GithubAccessToken, GithubError>> + Send;
+
/// Enriches GitHub pull request references with details from the GitHub API.
fn enrich_pull_requests(
&self,
diff --git a/crates/github/src/domain/service/link.rs b/crates/github/src/domain/service/link.rs
index 6f7cc96835..5e71db2df8 100644
--- a/crates/github/src/domain/service/link.rs
+++ b/crates/github/src/domain/service/link.rs
@@ -229,6 +229,15 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Github
}
}
+ // No `err`: a missing link and an expired token are expected answers.
+ #[tracing::instrument(skip(self))]
+ async fn get_user_access_token(
+ &self,
+ macro_user_id: &MacroUserId<Lowercase<'static>>,
+ ) -> Result<GithubAccessToken, GithubError> {
+ self.validated_access_token(macro_user_id).await
+ }
+
#[tracing::instrument(skip(self, pull_requests), err)]
async fn enrich_pull_requests(
&self,
diff --git a/crates/macro_db_client/migrations/20261029152749_overlay_github_mcp.sql b/crates/macro_db_client/migrations/20261029152749_overlay_github_mcp.sql
new file mode 100644
index 0000000000..99a32fe1d4
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261029152749_overlay_github_mcp.sql
@@ -0,0 +1,7 @@
+-- GitHub connects through its own MCP server, authorized by the user's Macro
+-- GitHub account link (the same GitHub App) rather than a Pipedream grant, so
+-- a user connects GitHub once. No non-MCP reader uses a Pipedream GitHub
+-- grant; existing ones stop being read and the app asks the user to link.
+INSERT INTO mcp_overlays (app_slug, server_url)
+VALUES ('github', 'https://api.githubcopilot.com/mcp')
+ON CONFLICT (app_slug) DO UPDATE SET server_url = EXCLUDED.server_url;
diff --git a/crates/mcp_client/AGENTS.md b/crates/mcp_client/AGENTS.md
index a7b11cd823..8d371afe06 100644
--- a/crates/mcp_client/AGENTS.md
+++ b/crates/mcp_client/AGENTS.md
@@ -25,6 +25,11 @@ through `rmcp`, returning the result to the caller's tool-calling loop.
port the outbound adapters implement.
- `src/domain/provider_registry.rs` (feature `providers`): pre-registered
OAuth credentials for known MCP providers, keyed off `macro_env_var`.
+- `src/domain/service/linked_github.rs`: `WithLinkedGithub`, the store
+ decorator that answers GitHub's MCP server with the user's GitHub account
+ link token (same GitHub App), read through the `LinkedGithubTokens` port
+ (`outbound/auth_service_github_tokens.rs`). Hosts read the native store as
+ `outbound::NativeServerStore`.
- `src/inbound/axum_router.rs`: HTTP routes for server management and the
OAuth callback.
- `src/inbound/toolset.rs`: the `ConnectMcpServer` AI tool, wired through
@@ -41,7 +46,8 @@ through `rmcp`, returning the result to the caller's tool-calling loop.
## Boundaries
-- Depends on: `agent`, `ai_toolset`, `macro_authorization` (feature `axum`),
+- Depends on: `agent`, `ai_toolset`, `authentication_service_client`,
+ `macro_authorization` (feature `axum`),
`macro_user_id`, `rmcp`.
- Used by: `agent_egress`, `agent_harness`, `ai_tools`, `mcp_select`,
`onboarding`.
diff --git a/crates/mcp_client/Cargo.toml b/crates/mcp_client/Cargo.toml
index 2b9e726dbd..756688b12a 100644
--- a/crates/mcp_client/Cargo.toml
+++ b/crates/mcp_client/Cargo.toml
@@ -13,6 +13,7 @@ aes-gcm = "0.10"
agent = { path = "../agent" }
ai_toolset = { path = "../ai_toolset" }
anyhow.workspace = true
+authentication_service_client = { path = "../authentication_service_client" }
async-trait.workspace = true
oauth2 = { version = "5.0", default-features = false }
base64.workspace = true
diff --git a/crates/mcp_client/src/domain/models/consts.rs b/crates/mcp_client/src/domain/models/consts.rs
index 43a6e061e5..d6d6a9e7d2 100644
--- a/crates/mcp_client/src/domain/models/consts.rs
+++ b/crates/mcp_client/src/domain/models/consts.rs
@@ -1,2 +1,6 @@
/// Our MCP client publishes this name to servers on-connect
pub const MCP_CLIENT_NAME: &str = "Macro";
+
+/// GitHub's hosted MCP server. A user's Macro GitHub account link authorizes
+/// it; see [`crate::domain::service::WithLinkedGithub`].
+pub const GITHUB_MCP_SERVER_URL: &str = "https://api.githubcopilot.com/mcp";
diff --git a/crates/mcp_client/src/domain/ports.rs b/crates/mcp_client/src/domain/ports.rs
index ad4b83a426..2aa2245638 100644
--- a/crates/mcp_client/src/domain/ports.rs
+++ b/crates/mcp_client/src/domain/ports.rs
@@ -107,3 +107,17 @@ pub trait OAuthClient: Send + Sync + 'static {
state: &str,
) -> impl Future<Output = anyhow::Result<McpServerRecord>> + Send;
}
+
+/// The GitHub token from a user's Macro account link.
+///
+/// Object-safe (`async_trait`) so hosts without the link wire nothing and the
+/// decorated store's type stays the same everywhere.
+#[async_trait::async_trait]
+pub trait LinkedGithubTokens: Send + Sync + 'static {
+ /// The user's working link token; `None` when they never linked or the
+ /// token stopped working.
+ async fn access_token(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ ) -> anyhow::Result<Option<String>>;
+}
diff --git a/crates/mcp_client/src/domain/provider_registry.rs b/crates/mcp_client/src/domain/provider_registry.rs
index c81a31df43..0bc8cdeba8 100644
--- a/crates/mcp_client/src/domain/provider_registry.rs
+++ b/crates/mcp_client/src/domain/provider_registry.rs
@@ -4,7 +4,7 @@ use super::models;
/// Slack MCP server URL.
const SLACK_SERVER_URL: &str = "https://mcp.slack.com/mcp";
-const GITHUB_SERVER_URL: &str = "https://api.githubcopilot.com/mcp";
+use super::models::GITHUB_MCP_SERVER_URL as GITHUB_SERVER_URL;
const LINEAR_SERVER_URL: &str = "https://mcp.linear.app/mcp";
macro_env_var::env_var! {
diff --git a/crates/mcp_client/src/domain/service/linked_github.rs b/crates/mcp_client/src/domain/service/linked_github.rs
new file mode 100644
index 0000000000..019c9f56d2
--- /dev/null
+++ b/crates/mcp_client/src/domain/service/linked_github.rs
@@ -0,0 +1,154 @@
+//! GitHub's MCP server, authorized by the user's Macro GitHub account link.
+//!
+//! The account link and GitHub's MCP server use the same GitHub App, so the
+//! link's token is a valid bearer there. Rather than ask the user to
+//! authorize GitHub a second time, this store decorator answers every read
+//! of GitHub's server with the link's token: a linked user has GitHub
+//! connected wherever native MCP servers are read (chat, agent sessions,
+//! sandbox egress, discovery), and an unlinked one does not.
+//!
+//! The token is never persisted. It carries no expiry, so nothing tries to
+//! refresh it through MCP OAuth; when GitHub stops accepting it the link
+//! reports reauthentication and the server reads as disconnected until the
+//! user links again. A stored row for GitHub still holds the user's
+//! enabled toggle.
+
+use std::sync::Arc;
+
+use oauth2::basic::BasicTokenType;
+use oauth2::{AccessToken, StandardTokenResponse};
+use rmcp::transport::auth::VendorExtraTokenFields;
+
+use crate::domain::models::{
+ GITHUB_MCP_SERVER_URL, MacroUserIdStr, McpServerRecord, StoredCredentials,
+};
+use crate::domain::ports::{LinkedGithubTokens, McpServerStore};
+
+#[cfg(test)]
+mod test;
+
+/// Marks credentials that came from the account link rather than an MCP
+/// OAuth grant, so a save never persists them.
+const LINKED_CLIENT_ID: &str = "macro-github-link";
+
+/// Name of the GitHub server a linked user has without having added it.
+const GITHUB_SERVER_NAME: &str = "GitHub";
+
+fn is_github(url: &str) -> bool {
+ url.trim_end_matches('/') == GITHUB_MCP_SERVER_URL
+}
+
+fn linked_credentials(token: String) -> StoredCredentials {
+ StoredCredentials::new(
+ LINKED_CLIENT_ID.to_owned(),
+ Some(StandardTokenResponse::new(
+ AccessToken::new(token),
+ BasicTokenType::Bearer,
+ VendorExtraTokenFields::default(),
+ )),
+ Vec::new(),
+ None,
+ )
+}
+
+fn is_linked(credentials: &StoredCredentials) -> bool {
+ credentials.client_id == LINKED_CLIENT_ID
+}
+
+/// An [`McpServerStore`] whose GitHub server is authorized by the account
+/// link. Without a token source it is `inner` unchanged.
+#[derive(Clone)]
+pub struct WithLinkedGithub<S> {
+ inner: S,
+ tokens: Option<Arc<dyn LinkedGithubTokens>>,
+}
+
+impl<S> WithLinkedGithub<S> {
+ /// Decorate `inner`; `None` for a host that cannot read account links.
+ pub fn new(inner: S, tokens: Option<Arc<dyn LinkedGithubTokens>>) -> Self {
+ Self { inner, tokens }
+ }
+
+ /// The link's token, or `None` when unlinked. A failed lookup reads as
+ /// unlinked: GitHub goes missing rather than every server failing.
+ async fn linked_token(&self, user_id: &MacroUserIdStr<'static>) -> Option<String> {
+ let tokens = self.tokens.as_ref()?;
+ tokens
+ .access_token(user_id)
+ .await
+ .inspect_err(|error| tracing::warn!(error=?error, "failed to read linked GitHub token"))
+ .ok()
+ .flatten()
+ }
+}
+
+impl<S: McpServerStore> McpServerStore for WithLinkedGithub<S> {
+ type Err = S::Err;
+
+ async fn save(&self, record: &McpServerRecord) -> Result<(), Self::Err> {
+ if record.credentials.as_ref().is_some_and(is_linked) {
+ // Keep the enabled toggle; the token lives with the link.
+ let mut stored = record.clone();
+ stored.credentials = None;
+ return self.inner.save(&stored).await;
+ }
+ self.inner.save(record).await
+ }
+
+ async fn load(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ server_url: &str,
+ ) -> Result<Option<McpServerRecord>, Self::Err> {
+ let stored = self.inner.load(user_id, server_url).await?;
+ if !is_github(server_url) {
+ return Ok(stored);
+ }
+ let Some(token) = self.linked_token(user_id).await else {
+ return Ok(stored);
+ };
+ Ok(Some(with_link(stored, user_id, token)))
+ }
+
+ async fn delete(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ server_url: &str,
+ ) -> Result<(), Self::Err> {
+ self.inner.delete(user_id, server_url).await
+ }
+
+ async fn list(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<McpServerRecord>, Self::Err> {
+ let mut records = self.inner.list(user_id).await?;
+ let Some(token) = self.linked_token(user_id).await else {
+ return Ok(records);
+ };
+ let stored = records
+ .iter()
+ .position(|record| is_github(&record.url))
+ .map(|index| records.remove(index));
+ records.push(with_link(stored, user_id, token));
+ Ok(records)
+ }
+}
+
+/// GitHub's record carrying the link's token, keeping a stored row's name
+/// and enabled toggle.
+fn with_link(
+ stored: Option<McpServerRecord>,
+ user_id: &MacroUserIdStr<'static>,
+ token: String,
+) -> McpServerRecord {
+ let mut record = stored.unwrap_or_else(|| McpServerRecord {
+ user_id: user_id.clone(),
+ url: GITHUB_MCP_SERVER_URL.to_owned(),
+ server_name: GITHUB_SERVER_NAME.to_owned(),
+ credentials: None,
+ enabled: true,
+ });
+ record.credentials = Some(linked_credentials(token));
+ record
+}
diff --git a/crates/mcp_client/src/domain/service/linked_github/test.rs b/crates/mcp_client/src/domain/service/linked_github/test.rs
new file mode 100644
index 0000000000..3cd5bc6eca
--- /dev/null
+++ b/crates/mcp_client/src/domain/service/linked_github/test.rs
@@ -0,0 +1,190 @@
+use super::*;
+use macro_user_id::cowlike::CowLike;
+use oauth2::TokenResponse as _;
+use std::sync::Mutex;
+
+/// In-memory store holding one user's rows by URL.
+#[derive(Default)]
+struct MemoryStore {
+ rows: Mutex<Vec<McpServerRecord>>,
+}
+
+impl MemoryStore {
+ fn holding(rows: Vec<McpServerRecord>) -> Self {
+ Self {
+ rows: Mutex::new(rows),
+ }
+ }
+
+ fn rows(&self) -> Vec<McpServerRecord> {
+ self.rows.lock().unwrap().clone()
+ }
+}
+
+impl McpServerStore for MemoryStore {
+ type Err = anyhow::Error;
+
+ async fn save(&self, record: &McpServerRecord) -> Result<(), Self::Err> {
+ let mut rows = self.rows.lock().unwrap();
+ rows.retain(|row| row.url != record.url);
+ rows.push(record.clone());
+ Ok(())
+ }
+
+ async fn load(
+ &self,
+ _user_id: &MacroUserIdStr<'static>,
+ server_url: &str,
+ ) -> Result<Option<McpServerRecord>, Self::Err> {
+ Ok(self.rows().into_iter().find(|row| row.url == server_url))
+ }
+
+ async fn delete(
+ &self,
+ _user_id: &MacroUserIdStr<'static>,
+ server_url: &str,
+ ) -> Result<(), Self::Err> {
+ self.rows
+ .lock()
+ .unwrap()
+ .retain(|row| row.url != server_url);
+ Ok(())
+ }
+
+ async fn list(
+ &self,
+ _user_id: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<McpServerRecord>, Self::Err> {
+ Ok(self.rows())
+ }
+}
+
+/// Answers every user with the same link state.
+struct FixedTokens(anyhow::Result<Option<String>>);
+
+#[async_trait::async_trait]
+impl LinkedGithubTokens for FixedTokens {
+ async fn access_token(
+ &self,
+ _user_id: &MacroUserIdStr<'static>,
+ ) -> anyhow::Result<Option<String>> {
+ match &self.0 {
+ Ok(token) => Ok(token.clone()),
+ Err(error) => Err(anyhow::anyhow!("{error}")),
+ }
+ }
+}
+
+const WIKI: &str = "https://wiki.example.com/mcp";
+
+fn user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned()
+}
+
+fn row(url: &str, enabled: bool) -> McpServerRecord {
+ McpServerRecord {
+ user_id: user(),
+ url: url.to_owned(),
+ server_name: "Stored".to_owned(),
+ credentials: None,
+ enabled,
+ }
+}
+
+fn store(
+ rows: Vec<McpServerRecord>,
+ tokens: Option<anyhow::Result<Option<String>>>,
+) -> WithLinkedGithub<MemoryStore> {
+ WithLinkedGithub::new(
+ MemoryStore::holding(rows),
+ tokens.map(|answer| Arc::new(FixedTokens(answer)) as Arc<dyn LinkedGithubTokens>),
+ )
+}
+
+fn bearer(record: &McpServerRecord) -> Option<String> {
+ let token = record.credentials.as_ref()?.token_response.as_ref()?;
+ Some(token.access_token().secret().to_owned())
+}
+
+#[tokio::test]
+async fn a_linked_user_has_github_connected_without_adding_it() {
+ let store = store(vec![row(WIKI, true)], Some(Ok(Some("ghu_link".into()))));
+
+ let records = store.list(&user()).await.unwrap();
+
+ let github = records
+ .iter()
+ .find(|record| record.url == GITHUB_MCP_SERVER_URL)
+ .expect("GitHub listed");
+ assert!(github.enabled);
+ assert_eq!(bearer(github).as_deref(), Some("ghu_link"));
+ assert_eq!(records.len(), 2);
+}
+
+#[tokio::test]
+async fn the_link_replaces_a_stored_github_grant_and_keeps_its_toggle() {
+ let github_url = format!("{GITHUB_MCP_SERVER_URL}/");
+ let store = store(
+ vec![row(&github_url, false)],
+ Some(Ok(Some("ghu_link".into()))),
+ );
+
+ let records = store.list(&user()).await.unwrap();
+
+ assert_eq!(records.len(), 1);
+ assert!(!records[0].enabled);
+ assert_eq!(bearer(&records[0]).as_deref(), Some("ghu_link"));
+}
+
+#[tokio::test]
+async fn an_unlinked_user_reads_the_stored_rows_unchanged() {
+ for tokens in [None, Some(Ok(None)), Some(Err(anyhow::anyhow!("down")))] {
+ let store = store(vec![row(WIKI, true)], tokens);
+
+ let records = store.list(&user()).await.unwrap();
+
+ assert_eq!(records.len(), 1);
+ assert_eq!(records[0].url, WIKI);
+ assert!(
+ store
+ .load(&user(), GITHUB_MCP_SERVER_URL)
+ .await
+ .unwrap()
+ .is_none()
+ );
+ }
+}
+
+#[tokio::test]
+async fn loading_github_answers_with_the_link() {
+ let store = store(Vec::new(), Some(Ok(Some("ghu_link".into()))));
+
+ let github = store
+ .load(&user(), GITHUB_MCP_SERVER_URL)
+ .await
+ .unwrap()
+ .expect("GitHub loaded");
+
+ assert_eq!(bearer(&github).as_deref(), Some("ghu_link"));
+ assert!(store.load(&user(), WIKI).await.unwrap().is_none());
+}
+
+#[tokio::test]
+async fn saving_the_linked_record_persists_the_toggle_but_never_the_token() {
+ let store = store(Vec::new(), Some(Ok(Some("ghu_link".into()))));
+ let mut github = store
+ .load(&user(), GITHUB_MCP_SERVER_URL)
+ .await
+ .unwrap()
+ .expect("GitHub loaded");
+ github.enabled = false;
+
+ store.save(&github).await.unwrap();
+
+ let rows = store.inner.rows();
+ assert_eq!(rows.len(), 1);
+ assert!(!rows[0].enabled);
+ assert!(rows[0].credentials.is_none());
+}
diff --git a/crates/mcp_client/src/domain/service/mod.rs b/crates/mcp_client/src/domain/service/mod.rs
index b27df76ee5..f38d262c95 100644
--- a/crates/mcp_client/src/domain/service/mod.rs
+++ b/crates/mcp_client/src/domain/service/mod.rs
@@ -1,3 +1,5 @@
+/// GitHub's MCP server, authorized by the Macro GitHub account link.
+pub mod linked_github;
/// Write-through OAuth credential store for MCP connections.
pub mod persisting_credential_store;
/// A live credential for a stored server, for callers that stamp headers
@@ -8,6 +10,7 @@ pub mod server_directory;
/// MCP tool set and combined tool set for the AI loop.
pub mod toolset;
+pub use linked_github::WithLinkedGithub;
pub use persisting_credential_store::PersistingCredentialStore;
pub use server_access::{ServerAccess, server_access, unexpired_access_token};
pub use server_directory::{AddServerError, AddedBy, AddedServer, ServerDirectory};
diff --git a/crates/mcp_client/src/outbound/auth_service_github_tokens.rs b/crates/mcp_client/src/outbound/auth_service_github_tokens.rs
new file mode 100644
index 0000000000..832822d8ac
--- /dev/null
+++ b/crates/mcp_client/src/outbound/auth_service_github_tokens.rs
@@ -0,0 +1,35 @@
+//! [`LinkedGithubTokens`] over the authentication service, which owns the
+//! GitHub account link.
+
+use authentication_service_client::AuthServiceClient;
+
+use crate::domain::models::MacroUserIdStr;
+use crate::domain::ports::LinkedGithubTokens;
+
+/// Reads link tokens from the authentication service on every call, so
+/// linking or unlinking GitHub shows up on the next read.
+pub struct AuthServiceGithubTokens {
+ client: AuthServiceClient,
+}
+
+impl AuthServiceGithubTokens {
+ /// Read tokens through `client`.
+ pub fn new(client: AuthServiceClient) -> Self {
+ Self { client }
+ }
+}
+
+#[async_trait::async_trait]
+impl LinkedGithubTokens for AuthServiceGithubTokens {
+ #[tracing::instrument(skip_all, err)]
+ async fn access_token(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ ) -> anyhow::Result<Option<String>> {
+ Ok(self
+ .client
+ .get_github_access_token(user_id.as_ref())
+ .await?
+ .map(|token| token.access_token))
+ }
+}
diff --git a/crates/mcp_client/src/outbound/mod.rs b/crates/mcp_client/src/outbound/mod.rs
index 98494580c2..588dc23ffb 100644
--- a/crates/mcp_client/src/outbound/mod.rs
+++ b/crates/mcp_client/src/outbound/mod.rs
@@ -1,6 +1,12 @@
+/// [`LinkedGithubTokens`](crate::domain::ports::LinkedGithubTokens) over the authentication service.
+pub mod auth_service_github_tokens;
/// RMCP-backed OAuth adapter for remote MCP servers.
pub mod oauth;
/// Postgres-backed repository implementing [`McpServerStore`](crate::domain::ports::McpServerStore).
pub mod pg_server_repo;
/// Redis-backed store implementing [`OAuthStateStore`](crate::domain::ports::OAuthStateStore).
pub mod redis_state_store;
+
+/// The native server store hosts read: the Postgres rows, with GitHub's
+/// server authorized by the user's account link.
+pub type NativeServerStore = crate::domain::service::WithLinkedGithub<pg_server_repo::PgServerRepo>;
diff --git a/crates/memory/src/context.rs b/crates/memory/src/context.rs
index 756c35fecd..ba9370cd48 100644
--- a/crates/memory/src/context.rs
+++ b/crates/memory/src/context.rs
@@ -26,6 +26,8 @@ pub async fn build_tool_service_context(
config.enable_ai_usage_enforcement,
config.ai_pricing,
recorder,
+ // No authentication service here: a linked GitHub account is not read.
+ None,
)
.await
}
diff --git a/crates/model/src/authentication/github_token.rs b/crates/model/src/authentication/github_token.rs
new file mode 100644
index 0000000000..e36c0f3162
--- /dev/null
+++ b/crates/model/src/authentication/github_token.rs
@@ -0,0 +1,14 @@
+/// A user's GitHub access token from their Macro account link.
+#[derive(serde::Serialize, serde::Deserialize)]
+pub struct GithubAccessToken {
+ /// The linked account's access token
+ pub access_token: String,
+}
+
+impl std::fmt::Debug for GithubAccessToken {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("GithubAccessToken")
+ .field("access_token", &"[redacted]")
+ .finish()
+ }
+}
diff --git a/crates/model/src/authentication/mod.rs b/crates/model/src/authentication/mod.rs
index bcc1a08820..487cb3c2e8 100644
--- a/crates/model/src/authentication/mod.rs
+++ b/crates/model/src/authentication/mod.rs
@@ -1,4 +1,5 @@
pub mod error;
+pub mod github_token;
pub mod google_token;
pub mod login;
pub mod permission;
diff --git a/crates/pipedream_mcp/AGENTS.md b/crates/pipedream_mcp/AGENTS.md
index 1114a1bd59..5fabecdef0 100644
--- a/crates/pipedream_mcp/AGENTS.md
+++ b/crates/pipedream_mcp/AGENTS.md
@@ -49,6 +49,9 @@ AI loop calls their tools through Pipedream's remote MCP server.
- Discovery answers an overlaid app's connection status through
`OverlayConnections` (implemented in `mcp_select` over the native store); its
advertised tools still come from Pipedream's listing for the slug.
+- `github` is overlaid, but its native server is authorized by the GitHub
+ account link (`mcp_client`'s `WithLinkedGithub`), not MCP OAuth; the
+ frontend connects it by linking the account.
## Checks
diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.md
index 9a3d782b0d..1781866db9 100644
--- a/docs/agent-guide/settings.md
+++ b/docs/agent-guide/settings.md
@@ -643,6 +643,13 @@ category) among the integrations in use, not with the custom MCP servers at
the top; native servers wait for the overlay list before rendering so one never
jumps. Verify with an overlaid app such as Sentry or Asana; completing a
Pipedream connection for one answers 409.
+GitHub is overlaid onto `api.githubcopilot.com/mcp`, but its server is
+authorized by the GitHub account link (the same GitHub App), so connecting
+GitHub anywhere (catalog, chat connect card, import dialog, the GitHub AI
+provider page) runs the account link, and a linked account shows GitHub
+connected for Macro AI with no second consent. Disconnecting GitHub on its AI
+provider page unlinks the account. Verify by linking GitHub from its row and
+checking the GitHub catalog entry reads connected.
The Agents workspace opens this same Integrations page. The list includes featured providers, a searchable catalog,
and `Add Custom`. Pipedream Slack OAuth is available in production and
development from the featured Slack provider. Connecting Slack here grants tool
diff --git a/services/agent_harness_service/src/cognition/api/context.rs b/services/agent_harness_service/src/cognition/api/context.rs
index 550146c17e..a27eb30969 100644
--- a/services/agent_harness_service/src/cognition/api/context.rs
+++ b/services/agent_harness_service/src/cognition/api/context.rs
@@ -108,9 +108,9 @@ pub type DcsAiProjectionService =
/// Concrete MCP router state for DCS.
pub type DcsMcpRouterState = mcp_client::inbound::McpRouterState<
- mcp_client::outbound::pg_server_repo::PgServerRepo,
+ mcp_client::outbound::NativeServerStore,
mcp_client::outbound::oauth::OAuthService<
- mcp_client::outbound::pg_server_repo::PgServerRepo,
+ mcp_client::outbound::NativeServerStore,
mcp_client::outbound::redis_state_store::RedisOAuthStateStore,
>,
DcsAuthorizationService,
@@ -124,7 +124,7 @@ pub type DcsImportService = ai_tools::ToolImportService;
/// store.
pub type DcsOnboardingService = onboarding::domain::service::OnboardingServiceImpl<
onboarding::outbound::pg_onboarding_repo::PgOnboardingRepo,
- mcp_client::outbound::pg_server_repo::PgServerRepo,
+ mcp_client::outbound::NativeServerStore,
>;
/// Concrete Pipedream MCP router state for DCS: the Postgres connection
diff --git a/services/agent_harness_service/src/cognition/api/context/test.rs b/services/agent_harness_service/src/cognition/api/context/test.rs
index 896bd896b6..2d4f77a1a2 100644
--- a/services/agent_harness_service/src/cognition/api/context/test.rs
+++ b/services/agent_harness_service/src/cognition/api/context/test.rs
@@ -599,8 +599,10 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
let (import_service, onboarding_service, mcp_selector) = {
let mcp_key =
mcp_client::domain::models::AesKey::try_from(vec![0u8; 32]).expect("valid test key");
- let mcp_repo =
- mcp_client::outbound::pg_server_repo::PgServerRepo::new(pool.clone(), mcp_key);
+ let mcp_repo = mcp_client::outbound::NativeServerStore::new(
+ mcp_client::outbound::pg_server_repo::PgServerRepo::new(pool.clone(), mcp_key),
+ None,
+ );
let creator = ai_tools::ToolEntityCreator {
document_creator: document_tool_context.creator.clone(),
entity_access_service: entity_access_service.clone(),
@@ -825,8 +827,10 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
Arc::new(redis::Client::open("redis://127.0.0.1:6379/").expect("valid redis url"));
let mcp_key = mcp_client::domain::models::AesKey::try_from(vec![0u8; 32])
.expect("valid test key");
- let mcp_repo =
- mcp_client::outbound::pg_server_repo::PgServerRepo::new(pool.clone(), mcp_key);
+ let mcp_repo = mcp_client::outbound::NativeServerStore::new(
+ mcp_client::outbound::pg_server_repo::PgServerRepo::new(pool.clone(), mcp_key),
+ None,
+ );
let mcp_state_store =
mcp_client::outbound::redis_state_store::RedisOAuthStateStore::new(redis_client);
let client_metadata = mcp_client::domain::models::OAuthClientMetadata::new(
diff --git a/services/agent_harness_service/src/cognition/server.rs b/services/agent_harness_service/src/cognition/server.rs
index 8cf58ddb59..268dfc9e55 100644
--- a/services/agent_harness_service/src/cognition/server.rs
+++ b/services/agent_harness_service/src/cognition/server.rs
@@ -546,7 +546,7 @@ pub async fn build(
.with_enforcement(config.enable_ai_usage_enforcement),
),
ai_billing.clone(),
- ai_billing::outbound::HttpSettlementTrigger::new(auth_service_client),
+ ai_billing::outbound::HttpSettlementTrigger::new(auth_service_client.clone()),
config.enable_ai_usage_billing,
));
@@ -580,8 +580,14 @@ pub async fn build(
)
.context("invalid MCP credentials encryption key")?;
let granola_signing_key = *mcp_encryption_key.as_bytes();
- let mcp_server_repo =
- mcp_client::outbound::pg_server_repo::PgServerRepo::new(db.clone(), mcp_encryption_key);
+ let mcp_server_repo = mcp_client::outbound::NativeServerStore::new(
+ mcp_client::outbound::pg_server_repo::PgServerRepo::new(db.clone(), mcp_encryption_key),
+ Some(Arc::new(
+ mcp_client::outbound::auth_service_github_tokens::AuthServiceGithubTokens::new(
+ (*auth_service_client).clone(),
+ ),
+ )),
+ );
// The Pipedream MCP stack, fully separate from the native one above
// (own endpoints, own table, own toolset). Without credentials its
diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rs
index 3f789da878..90323fff82 100644
--- a/services/agent_harness_service/src/config.rs
+++ b/services/agent_harness_service/src/config.rs
@@ -304,23 +304,42 @@ impl Config {
/// while `ENABLE_AI_USAGE_BILLING` is true, which then requires
/// `AUTHENTICATION_SERVICE_SECRET_KEY`; nowhere otherwise.
pub fn settlement_route(&self) -> anyhow::Result<ai_billing::composition::SettlementRoute> {
- let client = self
- .authentication_service_secret_key
+ Ok(ai_billing::composition::SettlementRoute::from_policy(
+ self.enable_ai_usage_billing,
+ self.auth_service_client()?.map(std::sync::Arc::new),
+ )?)
+ }
+
+ /// The authentication service client, when
+ /// `AUTHENTICATION_SERVICE_SECRET_KEY` is set.
+ pub fn auth_service_client(
+ &self,
+ ) -> anyhow::Result<Option<authentication_service_client::AuthServiceClient>> {
+ self.authentication_service_secret_key
.value()
.filter(|key| !key.trim().is_empty())
.map(|key| {
- anyhow::Ok(std::sync::Arc::new(
- authentication_service_client::AuthServiceClient::new(
- key.to_owned(),
- macro_service_urls::AuthServiceUrl::new()?.to_string(),
- ),
+ anyhow::Ok(authentication_service_client::AuthServiceClient::new(
+ key.to_owned(),
+ macro_service_urls::AuthServiceUrl::new()?.to_string(),
))
})
- .transpose()?;
- Ok(ai_billing::composition::SettlementRoute::from_policy(
- self.enable_ai_usage_billing,
- client,
- )?)
+ .transpose()
+ }
+
+ /// Reads GitHub account-link tokens, so GitHub's MCP server needs no
+ /// separate authorization. `None` without the authentication service.
+ pub fn linked_github_tokens(
+ &self,
+ ) -> anyhow::Result<Option<std::sync::Arc<dyn mcp_client::domain::ports::LinkedGithubTokens>>>
+ {
+ Ok(self.auth_service_client()?.map(|client| {
+ std::sync::Arc::new(
+ mcp_client::outbound::auth_service_github_tokens::AuthServiceGithubTokens::new(
+ client,
+ ),
+ ) as std::sync::Arc<dyn mcp_client::domain::ports::LinkedGithubTokens>
+ }))
}
/// Load the configuration from the environment.
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 39b49dbc66..73fd913690 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -152,6 +152,7 @@ use macro_service_urls::{
StaticFilePublicUrl, StaticFileServiceUrl,
};
use mcp_client::domain::models::AesKey;
+use mcp_client::outbound::NativeServerStore;
use mcp_client::outbound::pg_server_repo::PgServerRepo;
use model_providers::{CursorModels, InMemoryModels, MacrodModels, VisibleHarnessAccess};
use permission_policy::PgPermissionPolicySource;
@@ -467,10 +468,15 @@ async fn run() -> anyhow::Result<()> {
let mcp_connections = Arc::new(PgConnectionRepo::new(pool.clone()));
// Custom MCP servers - the ones a person added by URL - in the same rows
// agent_harness_service::cognition manages, under the same encryption key, so
- // the proxy can refresh a stored grant and persist what comes back.
+ // the proxy can refresh a stored grant and persist what comes back. GitHub
+ // is authorized by the account link instead.
let mcp_credentials_key = AesKey::try_from(config.mcp_credentials_key_secret_name.as_ref())
.context("invalid MCP credentials encryption key")?;
- let mcp_servers = Arc::new(PgServerRepo::new(pool.clone(), mcp_credentials_key));
+ let linked_github = config.linked_github_tokens()?;
+ let mcp_servers = Arc::new(NativeServerStore::new(
+ PgServerRepo::new(pool.clone(), mcp_credentials_key),
+ linked_github.clone(),
+ ));
// The client that addresses Pipedream's remote MCP server, built from the
// same credentials `agent_harness_service::cognition` uses.
@@ -574,6 +580,7 @@ async fn run() -> anyhow::Result<()> {
config.enable_ai_usage_enforcement,
config.ai_pricing(),
recorder.clone(),
+ linked_github,
)
.await
.context("failed to build the in-memory agent tool context")?;
diff --git a/services/authentication_service/src/api/internal.rs b/services/authentication_service/src/api/internal.rs
index 86e2fa8d19..13e321133b 100644
--- a/services/authentication_service/src/api/internal.rs
+++ b/services/authentication_service/src/api/internal.rs
@@ -9,6 +9,7 @@ use super::user::post_get_names;
// needs to be public in api crate for swagger
mod delete_inbox_grant_user;
+mod github_access_token;
mod google_access_token;
mod microsoft_access_token;
mod microsoft_grant;
@@ -22,6 +23,7 @@ mod fusionauth_fixture;
pub fn router() -> Router<ApiContext> {
Router::new()
+ .route("/github_access_token", get(github_access_token::handler))
.route("/google_access_token", get(google_access_token::handler))
.route("/microsoft_grant", get(microsoft_grant::handler))
.route(
diff --git a/services/authentication_service/src/api/internal/github_access_token.rs b/services/authentication_service/src/api/internal/github_access_token.rs
new file mode 100644
index 0000000000..9344ff34d0
--- /dev/null
+++ b/services/authentication_service/src/api/internal/github_access_token.rs
@@ -0,0 +1,65 @@
+use axum::{
+ Json,
+ extract::{self, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+};
+use github::domain::{models::GithubError, ports::GithubLinkService};
+use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserId};
+use model::authentication::github_token::GithubAccessToken;
+use model::response::ErrorResponse;
+
+use crate::api::context::{ApiContext, AuthorizationService};
+
+#[derive(serde::Deserialize, Debug)]
+pub struct GithubAccessTokenParams {
+ macro_user_id: String,
+}
+
+/// The user's GitHub token from their account link: 404 when they never
+/// linked, 428 when the token no longer works and they must link again.
+#[tracing::instrument(skip(ctx, _internal_authorization))]
+pub async fn handler(
+ State(ctx): State<ApiContext>,
+ _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
+ extract::Query(params): extract::Query<GithubAccessTokenParams>,
+) -> Response {
+ let Ok(user_id) = MacroUserId::parse_from_str(&params.macro_user_id.to_lowercase())
+ .map(|id| id.into_owned().lowercase())
+ else {
+ return error_response(StatusCode::BAD_REQUEST, "invalid macro user id");
+ };
+
+ match ctx
+ .github_link_service
+ .get_user_access_token(&user_id)
+ .await
+ {
+ Ok(token) => Json(GithubAccessToken {
+ access_token: token.as_str().to_owned(),
+ })
+ .into_response(),
+ Err(GithubError::NoLinkFound) => {
+ error_response(StatusCode::NOT_FOUND, "no github link found")
+ }
+ Err(GithubError::ReauthenticationRequired) => error_response(
+ StatusCode::PRECONDITION_REQUIRED,
+ "github reauthentication required",
+ ),
+ Err(error) => {
+ tracing::error!(error=?error, "failed to read github access token");
+ error_response(StatusCode::INTERNAL_SERVER_ERROR, "internal error")
+ }
+ }
+}
+
+fn error_response(status_code: StatusCode, message: &'static str) -> Response {
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: message.into(),
+ }),
+ )
+ .into_response()
+}
diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.toml
index c575d222d2..56d7dd84e3 100644
--- a/services/document_storage_service/Cargo.toml
+++ b/services/document_storage_service/Cargo.toml
@@ -197,6 +197,7 @@ opentelemetry = { workspace = true }
tracing-opentelemetry = { workspace = true }
macro_tower_layers = { path = "../../crates/macro_tower_layers" }
macro_user_id = { path = "../../crates/macro_user_id" }
+mcp_client = { path = "../../crates/mcp_client" }
macro_uuid = { path = "../../crates/macro_uuid" }
mockall = { workspace = true }
model = { path = "../../crates/model" }
diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rs
index bb1b7ecc2c..19cec21fd8 100644
--- a/services/document_storage_service/src/server.rs
+++ b/services/document_storage_service/src/server.rs
@@ -1393,6 +1393,17 @@ pub async fn run() -> anyhow::Result<()> {
config.enable_ai_usage_enforcement,
config.ai_pricing(),
ai_usage::pg_recorder_with_enforcement(db.clone(), config.enable_ai_usage_enforcement),
+ Some(Arc::new(
+ mcp_client::outbound::auth_service_github_tokens::AuthServiceGithubTokens::new(
+ authentication_service_client::AuthServiceClient::new(
+ config
+ .authentication_service_secret_key
+ .as_ref()
+ .to_string(),
+ macro_service_urls::AuthServiceUrl::new()?.to_string(),
+ ),
+ ),
+ )),
)
.await
.context("failed to build Macro agent tool context")?;