Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ai): mcp server (#2060)
Eric Hayes4e924a1c0740
diff --git a/.github/services-config.json b/.github/services-config.jsonindex 824f061238..dd6258c5e9 100644--- a/.github/services-config.json+++ b/.github/services-config.json@@ -144,6 +144,13 @@"rust/cloud-storage/image_proxy_service/**"],"stack_path": "infra/stacks/image-proxy-service/**"+ },+ "mcp-server": {+ "source_paths": [+ "rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs",+ "rust/cloud-storage/document_cognition_service/src/mcp_oauth/**"+ ],+ "stack_path": "infra/stacks/mcp-server/**"}}}diff --git a/.github/workflows/deploy-service-generic.yml b/.github/workflows/deploy-service-generic.ymlindex 6cf2df1072..26581135c5 100644--- a/.github/workflows/deploy-service-generic.yml+++ b/.github/workflows/deploy-service-generic.yml@@ -24,6 +24,7 @@ on:- image-proxy-service- lambda-aggregate-frecency- link-sharing+ - mcp-server- notification-service- organization-retention- search-processing-servicediff --git a/infra/bun.lock b/infra/bun.lockindex 41b31a50f4..b5dd234254 100644--- a/infra/bun.lock+++ b/infra/bun.lock@@ -134,6 +134,10 @@"name": "macrodb-stack","version": "0.0.0",},+ "stacks/mcp-server": {+ "name": "mcp-server-stack",+ "version": "0.0.0",+ },"stacks/notification-service": {"name": "notification-service-stack","version": "0.0.0",@@ -748,6 +752,8 @@"make-fetch-happen": ["[email protected]", "", { "dependencies": { "@npmcli/agent": "^2.0.0", "cacache": "^18.0.0", "http-cache-semantics": "^4.1.1", "is-lambda": "^1.0.1", "minipass": "^7.0.2", "minipass-fetch": "^3.0.0", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "negotiator": "^0.6.3", "proc-log": "^4.2.0", "promise-retry": "^2.0.1", "ssri": "^10.0.0" } }, "sha512-cKTUFc/rbKUd/9meOvgrpJ2WrNzymt6jfRDdwg5UCnVzv9dTpEj9JS5m3wtziXVCjluIXyL8pcaukYqezIzZQA=="],+ "mcp-server-stack": ["mcp-server-stack@workspace:stacks/mcp-server"],+"merge-stream": ["[email protected]", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="],"mime": ["[email protected]", "", { "bin": { "mime": "cli.js" } }, "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg=="],diff --git a/infra/stacks/fusionauth-instance/index.ts b/infra/stacks/fusionauth-instance/index.tsindex fbd73aacf6..2f48c724b3 100644--- a/infra/stacks/fusionauth-instance/index.ts+++ b/infra/stacks/fusionauth-instance/index.ts@@ -262,6 +262,7 @@ const macroApplication = new FusionAuthApplication(authorizedUrlValidationPolicy: 'ExactMatch',authorizedRedirectUrls: [`${AUTHENTICATION_SERVICE_DOMAIN}/oauth/redirect`,+ `https://mcp-server${stack === 'prod' ? '' : `-${stack}`}.macro.com/oauth/callback`,],authorizedOriginUrls: ALLOWED_ORIGINS(),logoutBehavior: 'AllApplications',diff --git a/infra/stacks/link-sharing/file-storage-bucket.ts b/infra/stacks/link-sharing/file-storage-bucket.tsindex 171c8eb2d7..b37b48a0d4 100644--- a/infra/stacks/link-sharing/file-storage-bucket.ts+++ b/infra/stacks/link-sharing/file-storage-bucket.ts@@ -45,6 +45,7 @@ export const attachPolicyToBucket = ({bulkUploadLambdaRoleArn,convertServiceRoleArn,documentCognitionRoleArn,+ mcpServerRoleArn,}: {cloudfrontDistributionArn: pulumi.Output<string>;bucket: pulumi.Output<GetStorageBucketResult>;@@ -59,6 +60,7 @@ export const attachPolicyToBucket = ({bulkUploadLambdaRoleArn: pulumi.Output<string>;convertServiceRoleArn: pulumi.Output<string>;documentCognitionRoleArn: pulumi.Output<string>;+ mcpServerRoleArn: pulumi.Output<string>;}) => {const groupName = config.require('adminGroupName');@@ -88,6 +90,7 @@ export const attachPolicyToBucket = ({bulkUploadLambdaRoleArn,convertServiceRoleArn,documentCognitionRoleArn,+ mcpServerRoleArn,];});@@ -225,6 +228,20 @@ export const attachPolicyToBucket = ({],Resource: [bucket.arn, pulumi.interpolate`${bucket.arn}/*`],},+ {+ Sid: 'AllowAccessForMcpServer',+ Effect: 'Allow',+ Principal: {+ AWS: mcpServerRoleArn,+ },+ Action: [+ 's3:ListBucket',+ 's3:GetObject',+ 's3:PutObject',+ 's3:DeleteObject',+ ],+ Resource: [bucket.arn, pulumi.interpolate`${bucket.arn}/*`],+ },{Sid: 'AllowCloudFrontServicePrincipal',Effect: 'Allow',diff --git a/infra/stacks/link-sharing/index.ts b/infra/stacks/link-sharing/index.tsindex 7a681ca949..72179a1a4a 100644--- a/infra/stacks/link-sharing/index.ts+++ b/infra/stacks/link-sharing/index.ts@@ -133,6 +133,14 @@ const documentCognitionRoleArn: pulumi.Output<string> = documentCognitionStack.getOutput('documentCognitionServiceRoleArn').apply((arn) => arn as string);+const mcpServerStack = new pulumi.StackReference('mcp-server-stack', {+ name: `macro-inc/mcp-server/${stack}`,+});++const mcpServerRoleArn: pulumi.Output<string> = mcpServerStack+ .getOutput('mcpServerRoleArn')+ .apply((arn) => arn as string);+export const bucketPolicy = attachPolicyToBucket({cloudfrontDistributionArn: s3CloudfrontDistribution.distribution.arn,bucket: fileStorageBucket,@@ -147,4 +155,5 @@ export const bucketPolicy = attachPolicyToBucket({bulkUploadLambdaRoleArn,convertServiceRoleArn,documentCognitionRoleArn,+ mcpServerRoleArn,});diff --git a/infra/stacks/mcp-server/Pulumi.dev.yaml b/infra/stacks/mcp-server/Pulumi.dev.yamlnew file mode 100644index 0000000000..a66f386d3e--- /dev/null+++ b/infra/stacks/mcp-server/Pulumi.dev.yaml@@ -0,0 +1,16 @@+config:+ aws-native:region: us-east-1+ aws:region: us-east-1+ mcp-server:fusionauth_base_url: https://fusionauth-dev.macro.com+ mcp-server:fusionauth_client_id: fusionauth-client-id-key-dev+ mcp-server:fusionauth_client_secret: fusionauth-client-secret-dev+ mcp-server:fusionauth_tenant_id: 5e13f524-8d32-0454-81f8-061936256aa4+ mcp-server:fusionauth_api_key: fusionauth-api-key-dev+ mcp-server:fusionauth_issuer: fusionauth-dev.macro.com+ mcp-server:google_client_id: google-client-id-dev+ mcp-server:google_client_secret: google-client-secret-dev+ mcp-server:internal_auth_key: document-storage-service-auth-key-dev+ mcp-server:jwt_secret_key: fusionauth-jwt-secret-dev+ mcp-server:macro_db_secret_key: macro-db-dev+ mcp-server:sync_service_auth_key: sync-service-key-dev+ datadog:validate: "false"diff --git a/infra/stacks/mcp-server/Pulumi.yaml b/infra/stacks/mcp-server/Pulumi.yamlnew file mode 100644index 0000000000..db908dcc3e--- /dev/null+++ b/infra/stacks/mcp-server/Pulumi.yaml@@ -0,0 +1,3 @@+name: mcp-server+runtime: nodejs+description: Macro MCP Serverdiff --git a/infra/stacks/mcp-server/index.ts b/infra/stacks/mcp-server/index.tsnew file mode 100644index 0000000000..adf63995df--- /dev/null+++ b/infra/stacks/mcp-server/index.ts@@ -0,0 +1,290 @@+import * as aws from '@pulumi/aws';+import * as pulumi from '@pulumi/pulumi';+import { config, getMacroApiToken, stack } from '../../packages/shared';+import { get_coparse_api_vpc } from '../../packages/vpc';+import { McpServer, SERVICE_DOMAIN_NAME } from './mcp-server';++const tags = {+ environment: stack,+ env: stack,+ tech_lead: 'ehayes',+ project: 'mcp-server',+ service: 'mcp-server',+};++// ── Secrets ──────────────────────────────────────────────────────────────────++const DATABASE_URL = aws.secretsmanager+ .getSecretVersionOutput({+ secretId: config.require('macro_db_secret_key'),+ })+ .apply((secret) => secret.secretString);++const SYNC_SERVICE_AUTH_KEY = config.require('sync_service_auth_key');+const syncServiceAuthKeyArn: pulumi.Output<string> = aws.secretsmanager+ .getSecretVersionOutput({ secretId: SYNC_SERVICE_AUTH_KEY })+ .apply((secret) => secret.arn);++const JWT_SECRET_KEY = config.require('jwt_secret_key');+const jwtSecretKeyArn: pulumi.Output<string> = aws.secretsmanager+ .getSecretVersionOutput({ secretId: JWT_SECRET_KEY })+ .apply((secret) => secret.arn);++const fusionauthClientIdSecretKey = config.require('fusionauth_client_id');+const FUSIONAUTH_CLIENT_ID = aws.secretsmanager+ .getSecretVersionOutput({ secretId: fusionauthClientIdSecretKey })+ .apply((secret) => secret.secretString);++const FUSIONAUTH_BASE_URL = config.require('fusionauth_base_url');+const FUSIONAUTH_ISSUER = config.require('fusionauth_issuer');++const FUSIONAUTH_CLIENT_SECRET = config.require('fusionauth_client_secret');+const fusionauthClientSecretArn: pulumi.Output<string> = aws.secretsmanager+ .getSecretVersionOutput({ secretId: FUSIONAUTH_CLIENT_SECRET })+ .apply((secret) => secret.arn);++const FUSIONAUTH_TENANT_ID = config.require('fusionauth_tenant_id');++const FUSIONAUTH_API_KEY = config.require('fusionauth_api_key');+const fusionauthApiKeyArn: pulumi.Output<string> = aws.secretsmanager+ .getSecretVersionOutput({ secretId: FUSIONAUTH_API_KEY })+ .apply((secret) => secret.arn);++const googleClientIdSecretKey = config.require('google_client_id');+const GOOGLE_CLIENT_ID = aws.secretsmanager+ .getSecretVersionOutput({ secretId: googleClientIdSecretKey })+ .apply((secret) => secret.secretString);++const GOOGLE_CLIENT_SECRET = config.require('google_client_secret');+const googleClientSecretArn: pulumi.Output<string> = aws.secretsmanager+ .getSecretVersionOutput({ secretId: GOOGLE_CLIENT_SECRET })+ .apply((secret) => secret.arn);++const INTERNAL_AUTH_KEY = aws.secretsmanager+ .getSecretVersionOutput({+ secretId: config.require('internal_auth_key'),+ })+ .apply((secret) => secret.secretString);++const MACRO_API_TOKENS = getMacroApiToken();++// ── Stack references ─────────────────────────────────────────────────────────++export const coparse_api_vpc = get_coparse_api_vpc();++const cloudStorageStack = new pulumi.StackReference('cloud-storage-stack', {+ name: `macro-inc/document-storage/${stack}`,+});++const cloudStorageClusterArn: pulumi.Output<string> = cloudStorageStack+ .getOutput('cloudStorageClusterArn')+ .apply((arn) => arn as string);++const cloudStorageClusterName: pulumi.Output<string> = cloudStorageStack+ .getOutput('cloudStorageClusterName')+ .apply((arn) => arn as string);++const documentStorageBucketId: pulumi.Output<string> = cloudStorageStack+ .getOutput('documentStorageBucketId')+ .apply((id) => id as string);++const documentStorageBucketArn: pulumi.Output<string> = cloudStorageStack+ .getOutput('documentStorageBucketArn')+ .apply((arn) => arn as string);++const cloudStorageServiceStack = new pulumi.StackReference(+ 'cloud-storage-service',+ {+ name: `macro-inc/cloud-storage-service/${stack}`,+ }+);++export const documentStorageServiceUrl: pulumi.Output<string> =+ cloudStorageServiceStack+ .getOutput('cloudStorageServiceUrl')+ .apply((url) => url as string);++const docxUploadBucketName: pulumi.Output<string> = cloudStorageServiceStack+ .getOutput('docxUploadBucketName')+ .apply((name) => name as string);++const docxUploadBucketArn: pulumi.Output<string> = cloudStorageServiceStack+ .getOutput('docxUploadBucketArn')+ .apply((arn) => arn as string);++const linksharingStack = new pulumi.StackReference('linksharing-stack', {+ name: `macro-inc/link-sharing/${stack}`,+});++const cloudfrontDistributionUrl: pulumi.Output<string> = linksharingStack+ .getOutput('cloudfrontDistributionUrl')+ .apply((url) => url as string);++const cloudfrontSignerPublicKeyId: pulumi.Output<string> = linksharingStack+ .getOutput('cloudfrontDistributionPublicKeyId')+ .apply((key) => key as string);++const CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME = `linksharing-private-key-${stack}`;++const cloudfrontPrivateKeySecretArn: pulumi.Output<string> = aws.secretsmanager+ .getSecretOutput({+ name: CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME,+ })+ .apply((secret) => secret.arn);++// ── Service ──────────────────────────────────────────────────────────────────++const mcpServer = new McpServer(`mcp-server-${stack}`, {+ ecsClusterArn: cloudStorageClusterArn,+ cloudStorageClusterName,+ vpc: coparse_api_vpc,+ platform: {+ family: 'linux',+ architecture: 'amd64',+ },+ secretKeyArns: [+ jwtSecretKeyArn,+ syncServiceAuthKeyArn,+ fusionauthClientSecretArn,+ fusionauthApiKeyArn,+ googleClientSecretArn,+ cloudfrontPrivateKeySecretArn,+ MACRO_API_TOKENS.macroApiTokenPublicKeyArn,+ ],+ bucketArns: [documentStorageBucketArn, docxUploadBucketArn],+ serviceContainerPort: 8080,+ healthCheckPath: '/health',+ containerEnvVars: [+ {+ name: 'DATABASE_URL',+ value: pulumi.interpolate`${DATABASE_URL}`,+ },+ {+ name: 'ENVIRONMENT',+ value: stack,+ },+ {+ name: 'RUST_LOG',+ value: 'info',+ },+ {+ name: 'INTERNAL_API_SECRET_KEY',+ value: pulumi.interpolate`${INTERNAL_AUTH_KEY}`,+ },+ {+ name: 'DOCUMENT_STORAGE_BUCKET',+ value: pulumi.interpolate`${documentStorageBucketId}`,+ },+ {+ name: 'DOCUMENT_STORAGE_SERVICE_URL',+ value: pulumi.interpolate`${documentStorageServiceUrl}`,+ },+ {+ name: 'DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL',+ value: pulumi.interpolate`${cloudfrontDistributionUrl}`,+ },+ {+ name: 'DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID',+ value: pulumi.interpolate`${cloudfrontSignerPublicKeyId}`,+ },+ {+ name: 'DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME',+ value: CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME,+ },+ {+ name: 'DOCX_DOCUMENT_UPLOAD_BUCKET',+ value: pulumi.interpolate`${docxUploadBucketName}`,+ },+ {+ name: 'SYNC_SERVICE_AUTH_KEY',+ value: pulumi.interpolate`${SYNC_SERVICE_AUTH_KEY}`,+ },+ {+ name: 'SYNC_SERVICE_URL',+ value: `https://sync-service-${stack === 'dev' ? 'dev3' : 'prod2'}.macroverse.workers.dev`,+ },+ {+ name: 'LEXICAL_SERVICE_URL',+ value: `https://lexical-service-${stack}.macroverse.workers.dev`,+ },+ {+ name: 'EMAIL_SERVICE_URL',+ value: `https://email-service${+ stack === 'prod' ? '' : `-${stack}`+ }.macro.com`,+ },+ {+ name: 'STATIC_FILE_SERVICE_URL',+ value: `https://static-file-service${+ stack === 'prod' ? '' : `-${stack}`+ }.macro.com`,+ },+ {+ name: 'JWT_SECRET_KEY',+ value: pulumi.interpolate`${JWT_SECRET_KEY}`,+ },+ {+ name: 'AUDIENCE',+ value: pulumi.interpolate`${FUSIONAUTH_CLIENT_ID}`,+ },+ {+ name: 'ISSUER',+ value: pulumi.interpolate`${FUSIONAUTH_ISSUER}`,+ },+ // MCP OAuth / FusionAuth+ {+ name: 'MCP_PUBLIC_URL',+ value: `https://${SERVICE_DOMAIN_NAME}`,+ },+ {+ name: 'FUSIONAUTH_BASE_URL',+ value: FUSIONAUTH_BASE_URL,+ },+ {+ name: 'FUSIONAUTH_CLIENT_ID',+ value: pulumi.interpolate`${FUSIONAUTH_CLIENT_ID}`,+ },+ {+ name: 'FUSIONAUTH_CLIENT_SECRET_KEY',+ value: FUSIONAUTH_CLIENT_SECRET,+ },+ {+ name: 'FUSIONAUTH_TENANT_ID',+ value: FUSIONAUTH_TENANT_ID,+ },+ {+ name: 'FUSIONAUTH_API_KEY_SECRET_KEY',+ value: FUSIONAUTH_API_KEY,+ },+ {+ name: 'GOOGLE_CLIENT_ID',+ value: pulumi.interpolate`${GOOGLE_CLIENT_ID}`,+ },+ {+ name: 'GOOGLE_CLIENT_SECRET_KEY',+ value: GOOGLE_CLIENT_SECRET,+ },+ {+ name: 'MACRO_API_TOKEN_ISSUER',+ value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenIssuer}`,+ },+ {+ name: 'MACRO_API_TOKEN_PUBLIC_KEY',+ value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenPublicKey}`,+ },+ // Datadog+ {+ name: 'DD_SERVICE',+ value: 'mcp-server',+ },+ {+ name: 'DD_ENV',+ value: stack,+ },+ ],+ isPrivate: false,+ tags,+});++export const mcpServerUrl = pulumi.interpolate`${mcpServer.domain}`;+export const mcpServerRoleArn = mcpServer.role.arn;diff --git a/infra/stacks/mcp-server/mcp-server.ts b/infra/stacks/mcp-server/mcp-server.tsnew file mode 100644index 0000000000..43fc0b55fe--- /dev/null+++ b/infra/stacks/mcp-server/mcp-server.ts@@ -0,0 +1,547 @@+import * as aws from '@pulumi/aws';+import * as awsx from '@pulumi/awsx';+import * as pulumi from '@pulumi/pulumi';+import {+ DATADOG_API_KEY,+ datadogAgentContainer,+ fargateLogRouterSidecarContainer,+ serviceLoadBalancer,+} from '../../packages/resources';+import { EcrImage } from '../../packages/service';+import {+ BASE_DOMAIN,+ CLOUD_TRAIL_SNS_TOPIC_ARN,+ stack,+} from '../../packages/shared';++const BASE_NAME = 'mcp-server';+const BASE_PATH = '../../../rust/cloud-storage';++export const SERVICE_DOMAIN_NAME = `mcp-server${+ stack === 'prod' ? '' : `-${stack}`+}.${BASE_DOMAIN}`;++type CreateMcpServerArgs = {+ cloudStorageClusterName: pulumi.Output<string> | string;+ ecsClusterArn: pulumi.Output<string> | string;+ vpc: {+ vpcId: pulumi.Output<string> | string;+ publicSubnetIds: pulumi.Output<string[]> | string[];+ privateSubnetIds: pulumi.Output<string[]> | string[];+ };+ platform: { family: string; architecture: 'amd64' | 'arm64' };+ serviceContainerPort: number;+ isPrivate?: boolean;+ containerEnvVars: { name: string; value: pulumi.Output<string> | string }[];+ healthCheckPath: string;+ tags: { [key: string]: string };+ secretKeyArns: (pulumi.Output<string> | string)[];+ bucketArns: (pulumi.Output<string> | string)[];+};++export class McpServer extends pulumi.ComponentResource {+ public role: aws.iam.Role;+ public ecr: awsx.ecr.Repository;+ public serviceAlbSg: aws.ec2.SecurityGroup;+ public serviceSg: aws.ec2.SecurityGroup;+ public targetGroup: aws.lb.TargetGroup;+ public lb: aws.lb.LoadBalancer;+ public listener: aws.lb.Listener;+ public service: awsx.ecs.FargateService;+ public domain: string;+ public cloudStorageClusterName: pulumi.Output<string> | string;+ public tags: { [key: string]: string };++ constructor(+ name: string,+ {+ ecsClusterArn,+ vpc,+ platform,+ serviceContainerPort,+ healthCheckPath,+ isPrivate,+ containerEnvVars,+ cloudStorageClusterName,+ secretKeyArns,+ bucketArns,+ tags,+ }: CreateMcpServerArgs,+ opts?: pulumi.ComponentResourceOptions+ ) {+ super('my:components:McpServer', name, {}, opts);+ this.tags = tags;+ this.cloudStorageClusterName = cloudStorageClusterName;+ this.domain = `https://${SERVICE_DOMAIN_NAME}`;++ // ecr image+ const image = new EcrImage(+ `${BASE_NAME}-ecr-image-${stack}`,+ {+ repositoryId: `${BASE_NAME}-ecr-${stack}`,+ repositoryName: `${BASE_NAME}-${stack}`,+ imageId: `${BASE_NAME}-image-${stack}`,+ imagePath: BASE_PATH,+ dockerfile: 'Dockerfile',+ platform,+ buildArgs: {+ SERVICE_NAME: 'mcp_server',+ },+ tags: this.tags,+ },+ { parent: this }+ );+ this.ecr = image.ecr;++ // sg+ const sg = this.initializeSecurityGroups({+ vpcId: vpc.vpcId,+ serviceContainerPort,+ });+ this.serviceAlbSg = sg.serviceAlbSg;+ this.serviceSg = sg.serviceSg;++ // lb+ const { targetGroup, lb, listener } = serviceLoadBalancer(this, {+ serviceName: BASE_NAME,+ serviceContainerPort,+ healthCheckPath,+ vpc,+ albSecurityGroupId: this.serviceAlbSg.id,+ isPrivate,+ tags,+ idleTimeout: 3600,+ });+ this.targetGroup = targetGroup;+ this.lb = lb;+ this.listener = listener;++ // IAM policies+ const secretsManagerPolicy = new aws.iam.Policy(+ `${BASE_NAME}-secrets-manager-policy`,+ {+ name: `${BASE_NAME}-secrets-manager-policy-${stack}`,+ policy: {+ Version: '2012-10-17',+ Statement: [+ {+ Action: [+ 'secretsmanager:GetSecretValue',+ 'secretsmanager:DescribeSecret',+ ],+ Resource: secretKeyArns,+ Effect: 'Allow',+ },+ ],+ },+ tags: this.tags,+ },+ { parent: this }+ );++ const s3Policy = new aws.iam.Policy(+ `${BASE_NAME}-s3-bucket-policy`,+ {+ name: `${BASE_NAME}-s3-bucket-policy-${stack}`,+ policy: {+ Version: '2012-10-17',+ Statement: [+ {+ Action: [+ 's3:ListBucket',+ 's3:GetObject',+ 's3:PutObject',+ 's3:DeleteObject',+ ],+ Resource: bucketArns.flatMap((arn) => [+ arn,+ pulumi.interpolate`${arn}/*`,+ ]),+ Effect: 'Allow',+ },+ ],+ },+ tags: this.tags,+ },+ { parent: this }+ );++ this.role = new aws.iam.Role(+ `${BASE_NAME}-role`,+ {+ name: `${BASE_NAME}-role-${stack}`,+ assumeRolePolicy: {+ Version: '2012-10-17',+ Statement: [+ {+ Action: 'sts:AssumeRole',+ Principal: {+ Service: 'ecs-tasks.amazonaws.com',+ },+ Effect: 'Allow',+ Sid: '',+ },+ ],+ },+ managedPolicyArns: [secretsManagerPolicy.arn, s3Policy.arn],+ tags: this.tags,+ },+ { parent: this }+ );++ // service+ const service = new awsx.ecs.FargateService(+ `${BASE_NAME}`,+ {+ tags,+ cluster: ecsClusterArn,+ networkConfiguration: {+ subnets: vpc.privateSubnetIds,+ securityGroups: [this.serviceSg.id],+ },+ taskDefinitionArgs: {+ taskRole: {+ roleArn: this.role.arn,+ },+ containers: {+ log_router: fargateLogRouterSidecarContainer,+ datadog_agent: datadogAgentContainer,+ service: {+ name: BASE_NAME,+ image: image.image.imageUri,+ stopTimeout: 10,+ cpu: 1024,+ memory: 2048,+ environment: containerEnvVars,+ logConfiguration: {+ logDriver: 'awsfirelens',+ options: {+ Name: 'datadog',+ Host: 'http-intake.logs.us5.datadoghq.com',+ apikey: DATADOG_API_KEY,+ dd_service: 'mcp-server',+ dd_source: 'fargate',+ dd_tags: `project:mcp-server, env:${stack}`,+ provider: 'ecs',+ },+ },+ portMappings: [+ {+ appProtocol: 'http',+ name: `${BASE_NAME}-tcp-${stack}`,+ hostPort: serviceContainerPort,+ containerPort: serviceContainerPort,+ targetGroup,+ },+ ],+ },+ },+ runtimePlatform: {+ operatingSystemFamily: `${platform.family.toUpperCase()}`,+ cpuArchitecture: `${+ platform.architecture === 'amd64'+ ? 'X86_64'+ : platform.architecture.toUpperCase()+ }`,+ },+ },+ desiredCount: 1,+ },+ { parent: this }+ );++ this.service = service;++ this.setupAutoScaling();+ this.setupServiceAlarms();++ // domain record+ const zone = aws.route53.getZoneOutput({ name: BASE_DOMAIN });++ new aws.route53.Record(+ `${BASE_NAME}-domain-record`,+ {+ name: SERVICE_DOMAIN_NAME,+ type: 'A',+ zoneId: zone.zoneId,+ aliases: [+ {+ evaluateTargetHealth: false,+ name: this.lb.dnsName,+ zoneId: this.lb.zoneId,+ },+ ],+ },+ { parent: this }+ );++ // NOTE: DatadogServiceEntity requires DD_API_KEY/DD_APP_KEY env vars.+ // Uncomment once deploying via CI where those secrets are available.+ // new DatadogServiceEntity('mcp-server', {+ // serviceName: 'mcp-server',+ // owner: 'ehayes',+ // githubUrl: 'https://github.com/macro-inc/macro-api',+ // githubPath: 'cloud-storage/document-cognition-service/src/bin/mcp_server.rs',+ // });+ }++ initializeSecurityGroups({+ vpcId,+ serviceContainerPort,+ }: {+ vpcId: pulumi.Output<string> | string;+ serviceContainerPort: number;+ }) {+ const serviceAlbSg = new aws.ec2.SecurityGroup(+ `${BASE_NAME}-alb-sg-${stack}`,+ {+ name: `${BASE_NAME}-alb-sg-${stack}`,+ description: `${BASE_NAME} application load balancer security group`,+ vpcId,+ tags: this.tags,+ },+ { parent: this }+ );++ const serviceSg = new aws.ec2.SecurityGroup(+ `${BASE_NAME}-sg-${stack}`,+ {+ name: `${BASE_NAME}-sg-${stack}`,+ vpcId,+ description: `${BASE_NAME} security group that is attached directly to the service`,+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.vpc.SecurityGroupIngressRule(+ `${BASE_NAME}-alb-in`,+ {+ securityGroupId: serviceSg.id,+ description: 'Allow inbound traffic from the services ALB',+ referencedSecurityGroupId: serviceAlbSg.id,+ fromPort: serviceContainerPort,+ toPort: serviceContainerPort,+ ipProtocol: 'tcp',+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.vpc.SecurityGroupEgressRule(+ `${BASE_NAME}-all-out`,+ {+ securityGroupId: serviceSg.id,+ description: 'Allow all outbound',+ cidrIpv4: '0.0.0.0/0',+ ipProtocol: '-1',+ tags: this.tags,+ },+ { parent: this }+ );++ // ALB SG rules+ new aws.vpc.SecurityGroupIngressRule(+ `${BASE_NAME}-http`,+ {+ securityGroupId: serviceAlbSg.id,+ description: 'Allow inbound HTTP traffic',+ cidrIpv4: '0.0.0.0/0',+ fromPort: 80,+ ipProtocol: 'tcp',+ toPort: 80,+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.vpc.SecurityGroupIngressRule(+ `${BASE_NAME}-https`,+ {+ securityGroupId: serviceAlbSg.id,+ description: 'Allow inbound HTTPS traffic',+ cidrIpv4: '0.0.0.0/0',+ fromPort: 443,+ ipProtocol: 'tcp',+ toPort: 443,+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.vpc.SecurityGroupEgressRule(+ `${BASE_NAME}-out-service`,+ {+ description: 'Allow traffic to the service security group',+ securityGroupId: serviceAlbSg.id,+ referencedSecurityGroupId: serviceSg.id,+ fromPort: serviceContainerPort,+ ipProtocol: 'tcp',+ toPort: serviceContainerPort,+ tags: this.tags,+ },+ { parent: this }+ );++ return { serviceAlbSg, serviceSg };+ }++ setupAutoScaling() {+ if (!this.service) return;++ const serviceScalableTarget = new aws.appautoscaling.Target(+ `${BASE_NAME}-service-scalable-target-${stack}`,+ {+ maxCapacity: stack === 'prod' ? 10 : 3,+ minCapacity: 1,+ resourceId: pulumi.interpolate`service/${this.cloudStorageClusterName}/${this.service.service.name}`,+ scalableDimension: 'ecs:service:DesiredCount',+ serviceNamespace: 'ecs',+ tags: this.tags,+ },+ { parent: this }+ );++ const lbPortion: pulumi.Output<string> = this.lb.arn.apply((arn) => {+ const parts = arn.split(':loadbalancer/');+ return parts[1];+ });++ const tgPortion: pulumi.Output<string> = this.targetGroup.arn.apply(+ (arn) => {+ const parts = arn.split(':');+ return parts[parts.length - 1];+ }+ );++ const resourceLabel = pulumi.interpolate`${lbPortion}/${tgPortion}`;++ new aws.appautoscaling.Policy(+ `${BASE_NAME}-scaling-policy-request-count-${stack}`,+ {+ policyType: 'TargetTrackingScaling',+ resourceId: serviceScalableTarget.resourceId,+ scalableDimension: serviceScalableTarget.scalableDimension,+ serviceNamespace: serviceScalableTarget.serviceNamespace,+ targetTrackingScalingPolicyConfiguration: {+ targetValue: 1000,+ predefinedMetricSpecification: {+ predefinedMetricType: 'ALBRequestCountPerTarget',+ resourceLabel,+ },+ scaleInCooldown: 60,+ scaleOutCooldown: 120,+ },+ },+ { parent: this }+ );++ new aws.appautoscaling.Policy(+ `${BASE_NAME}-scaling-policy-cpu-${stack}`,+ {+ policyType: 'TargetTrackingScaling',+ resourceId: serviceScalableTarget.resourceId,+ scalableDimension: serviceScalableTarget.scalableDimension,+ serviceNamespace: serviceScalableTarget.serviceNamespace,+ targetTrackingScalingPolicyConfiguration: {+ targetValue: 70.0,+ predefinedMetricSpecification: {+ predefinedMetricType: 'ECSServiceAverageCPUUtilization',+ },+ scaleInCooldown: 100,+ scaleOutCooldown: 300,+ },+ },+ { parent: this }+ );++ new aws.appautoscaling.Policy(+ `${BASE_NAME}-scaling-policy-memory-${stack}`,+ {+ policyType: 'TargetTrackingScaling',+ resourceId: serviceScalableTarget.resourceId,+ scalableDimension: serviceScalableTarget.scalableDimension,+ serviceNamespace: serviceScalableTarget.serviceNamespace,+ targetTrackingScalingPolicyConfiguration: {+ targetValue: 70.0,+ predefinedMetricSpecification: {+ predefinedMetricType: 'ECSServiceAverageMemoryUtilization',+ },+ scaleInCooldown: 100,+ scaleOutCooldown: 300,+ },+ },+ { parent: this }+ );+ }++ setupServiceAlarms() {+ new aws.cloudwatch.MetricAlarm(+ `${BASE_NAME}-high-cpu-alarm`,+ {+ name: `${BASE_NAME}-high-cpu-alarm-${stack}`,+ metricName: 'CPUUtilization',+ namespace: 'AWS/ECS',+ statistic: 'Average',+ period: 180,+ evaluationPeriods: 1,+ threshold: 80,+ comparisonOperator: 'GreaterThanThreshold',+ dimensions: {+ ClusterName: this.cloudStorageClusterName,+ ServiceName: this.service.service.name,+ },+ alarmDescription: `High CPU usage alarm for ${BASE_NAME} service.`,+ actionsEnabled: true,+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.cloudwatch.MetricAlarm(+ `${BASE_NAME}-high-mem-alarm`,+ {+ name: `${BASE_NAME}-high-mem-alarm-${stack}`,+ metricName: 'MemoryUtilization',+ namespace: 'AWS/ECS',+ statistic: 'Average',+ period: 180,+ evaluationPeriods: 1,+ threshold: 80,+ comparisonOperator: 'GreaterThanThreshold',+ dimensions: {+ ClusterName: this.cloudStorageClusterName,+ ServiceName: this.service.service.name,+ },+ alarmDescription: `High Memory usage alarm for ${BASE_NAME} service.`,+ actionsEnabled: true,+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.cloudwatch.MetricAlarm(+ `${BASE_NAME}-http-5xx-alarm`,+ {+ name: `${BASE_NAME}-http-5xx-${stack}`,+ metricName: 'HTTPCode_ELB_5XX_Count',+ namespace: 'AWS/ApplicationELB',+ statistic: 'Sum',+ period: 180,+ evaluationPeriods: 1,+ threshold: 25,+ comparisonOperator: 'GreaterThanOrEqualToThreshold',+ dimensions: {+ LoadBalancer: this.lb.arn,+ },+ alarmDescription: `High HTTP 5XX count alarm for ${BASE_NAME} Load Balancer.`,+ actionsEnabled: true,+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],+ tags: this.tags,+ },+ { parent: this }+ );+ }+}diff --git a/infra/stacks/mcp-server/package.json b/infra/stacks/mcp-server/package.jsonnew file mode 100644index 0000000000..73f2eb4326--- /dev/null+++ b/infra/stacks/mcp-server/package.json@@ -0,0 +1,7 @@+{+ "name": "mcp-server-stack",+ "version": "0.0.0",+ "private": true,+ "license": "MIT",+ "main": "index.ts"+}diff --git a/infra/stacks/mcp-server/tsconfig.json b/infra/stacks/mcp-server/tsconfig.jsonnew file mode 100644index 0000000000..4082f16a5d--- /dev/null+++ b/infra/stacks/mcp-server/tsconfig.json@@ -0,0 +1,3 @@+{+ "extends": "../../tsconfig.json"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex d635e6a0f3..0feca9162c 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -16,7 +16,7 @@ checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"dependencies = ["cfg-if","cipher",- "cpufeatures",+ "cpufeatures 0.2.17",][[package]]@@ -543,9 +543,9 @@ dependencies = [[[package]]name = "async-trait"-version = "0.1.86"+version = "0.1.89"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "644dd749086bf3771a2fbc5f256fdb982d53f011c7d5d560304eafeecebce79d"+checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"dependencies = ["proc-macro2","quote",@@ -679,7 +679,7 @@ dependencies = ["log","num-rational","num-traits",- "pastey",+ "pastey 0.1.1","rayon","thiserror 2.0.17","v_frame",@@ -1714,7 +1714,7 @@ version = "0.23.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2f42a145ed2d10dce2191e1dcf30cfccfea9026660e143662ba5eec4017d5daa"dependencies = [- "darling",+ "darling 0.20.10","proc-macro2","quote","syn 2.0.98",@@ -1770,6 +1770,17 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"+[[package]]+name = "chacha20"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.0",+ "rand_core 0.10.0",+]+[[package]]name = "channels"version = "0.1.0"@@ -2357,6 +2368,15 @@ dependencies = ["libc",]+[[package]]+name = "cpufeatures"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"+dependencies = [+ "libc",+]+[[package]]name = "crc"version = "3.3.0"@@ -2541,7 +2561,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"dependencies = ["cfg-if",- "cpufeatures",+ "cpufeatures 0.2.17","curve25519-dalek-derive","digest","fiat-crypto",@@ -2567,8 +2587,18 @@ version = "0.20.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989"dependencies = [- "darling_core",- "darling_macro",+ "darling_core 0.20.10",+ "darling_macro 0.20.10",+]++[[package]]+name = "darling"+version = "0.23.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"+dependencies = [+ "darling_core 0.23.0",+ "darling_macro 0.23.0",][[package]]@@ -2585,13 +2615,37 @@ dependencies = ["syn 2.0.98",]+[[package]]+name = "darling_core"+version = "0.23.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0"+dependencies = [+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn 2.0.98",+]+[[package]]name = "darling_macro"version = "0.20.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806"dependencies = [- "darling_core",+ "darling_core 0.20.10",+ "quote",+ "syn 2.0.98",+]++[[package]]+name = "darling_macro"+version = "0.23.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"+dependencies = [+ "darling_core 0.23.0","quote","syn 2.0.98",]@@ -2749,7 +2803,7 @@ version = "0.20.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"dependencies = [- "darling",+ "darling 0.20.10","proc-macro2","quote","syn 2.0.98",@@ -2832,7 +2886,9 @@ dependencies = ["email_service_client","entity_access","frecency",+ "fusionauth","futures",+ "http 1.3.1","http-body-util","last_online_tracker","lazy_static",@@ -2861,12 +2917,14 @@ dependencies = ["redis","regex","reqwest",+ "rmcp","schemars","scribe","search_service_client","secretsmanager_client","serde","serde_json",+ "sha2","soup","sqlx","sqs_client",@@ -2882,6 +2940,8 @@ dependencies = ["tower-http","tracing","unfurl_service",+ "url",+ "urlencoding","utoipa","utoipa-swagger-ui","uuid",@@ -4214,6 +4274,20 @@ dependencies = ["windows-targets 0.52.6",]+[[package]]+name = "getrandom"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+ "rand_core 0.10.0",+ "wasip2",+ "wasip3",+]+[[package]]name = "gif"version = "0.14.0"@@ -4935,6 +5009,12 @@ dependencies = ["syn 2.0.98",]+[[package]]+name = "id-arena"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"+[[package]]name = "ident_case"version = "1.0.1"@@ -5353,6 +5433,12 @@ dependencies = ["spin 0.9.8",]+[[package]]+name = "leb128fmt"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"+[[package]]name = "lebe"version = "0.5.2"@@ -7084,6 +7170,12 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"+[[package]]+name = "pastey"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b867cad97c0791bbd3aaa6472142568c6c9e8f71937e98379f584cfb0cf35bec"+[[package]]name = "pbkdf2"version = "0.12.2"@@ -7665,6 +7757,12 @@ version = "0.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "640c9bd8497b02465aeef5375144c26062e0dcd5939dfcbb0f5db76cb8c17c73"+[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"+[[package]]name = "rand"version = "0.7.3"@@ -7700,6 +7798,17 @@ dependencies = ["zerocopy 0.8.17",]+[[package]]+name = "rand"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc266eb313df6c5c09c1c7b1fbe2510961e5bcd3add930c1e31f7ed9da0feff8"+dependencies = [+ "chacha20",+ "getrandom 0.4.2",+ "rand_core 0.10.0",+]+[[package]]name = "rand_chacha"version = "0.2.2"@@ -7758,6 +7867,12 @@ dependencies = ["zerocopy 0.8.17",]+[[package]]+name = "rand_core"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c8d0fd677905edcbeedbf2edb6494d676f0e98d54d5cf9bda0b061cb8fb8aba"+[[package]]name = "rand_hc"version = "0.2.0"@@ -8131,6 +8246,50 @@ dependencies = ["windows-sys 0.52.0",]+[[package]]+name = "rmcp"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba6b9d2f0efe2258b23767f1f9e0054cfbcac9c2d6f81a031214143096d7864f"+dependencies = [+ "async-trait",+ "base64 0.22.1",+ "bytes",+ "chrono",+ "futures",+ "http 1.3.1",+ "http-body 1.0.1",+ "http-body-util",+ "pastey 0.2.1",+ "pin-project-lite",+ "rand 0.10.0",+ "rmcp-macros",+ "schemars",+ "serde",+ "serde_json",+ "sse-stream",+ "thiserror 2.0.17",+ "tokio",+ "tokio-stream",+ "tokio-util",+ "tower-service",+ "tracing",+ "uuid",+]++[[package]]+name = "rmcp-macros"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab9d95d7ed26ad8306352b0d5f05b593222b272790564589790d210aa15caa9e"+dependencies = [+ "darling 0.23.0",+ "proc-macro2",+ "quote",+ "serde_json",+ "syn 2.0.98",+]+[[package]]name = "roles_and_permissions"version = "0.1.0"@@ -8952,7 +9111,7 @@ version = "3.12.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8d00caa5193a3c8362ac2b73be6b9e768aa5a4b2f721d8f4b339600c3cb51f8e"dependencies = [- "darling",+ "darling 0.20.10","proc-macro2","quote","syn 2.0.98",@@ -9019,7 +9178,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"dependencies = ["cfg-if",- "cpufeatures",+ "cpufeatures 0.2.17","digest",]@@ -9036,7 +9195,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8"dependencies = ["cfg-if",- "cpufeatures",+ "cpufeatures 0.2.17","digest",]@@ -9553,6 +9712,19 @@ dependencies = ["tracing",]+[[package]]+name = "sse-stream"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eb4dc4d33c68ec1f27d386b5610a351922656e1fdf5c05bbaad930cd1519479a"+dependencies = [+ "bytes",+ "futures-util",+ "http-body 1.0.1",+ "http-body-util",+ "pin-project-lite",+]+[[package]]name = "stable_deref_trait"version = "1.2.0"@@ -10794,6 +10966,24 @@ dependencies = ["wit-bindgen-rt",]+[[package]]+name = "wasip2"+version = "1.0.2+wasi-0.2.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"+dependencies = [+ "wit-bindgen",+]++[[package]]+name = "wasip3"+version = "0.4.0+wasi-0.3.0-rc-2026-01-06"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"+dependencies = [+ "wit-bindgen",+]+[[package]]name = "wasite"version = "0.1.0"@@ -10857,6 +11047,28 @@ dependencies = ["unicode-ident",]+[[package]]+name = "wasm-encoder"+version = "0.244.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"+dependencies = [+ "leb128fmt",+ "wasmparser",+]++[[package]]+name = "wasm-metadata"+version = "0.244.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"+dependencies = [+ "anyhow",+ "indexmap 2.12.1",+ "wasm-encoder",+ "wasmparser",+]+[[package]]name = "wasm-streams"version = "0.4.2"@@ -10870,6 +11082,18 @@ dependencies = ["web-sys",]+[[package]]+name = "wasmparser"+version = "0.244.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"+dependencies = [+ "bitflags 2.8.0",+ "hashbrown 0.15.2",+ "indexmap 2.12.1",+ "semver",+]+[[package]]name = "web-sys"version = "0.3.72"@@ -11283,6 +11507,26 @@ dependencies = ["windows-sys 0.48.0",]+[[package]]+name = "wit-bindgen"+version = "0.51.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"+dependencies = [+ "wit-bindgen-rust-macro",+]++[[package]]+name = "wit-bindgen-core"+version = "0.51.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"+dependencies = [+ "anyhow",+ "heck",+ "wit-parser",+]+[[package]]name = "wit-bindgen-rt"version = "0.33.0"@@ -11292,6 +11536,74 @@ dependencies = ["bitflags 2.8.0",]+[[package]]+name = "wit-bindgen-rust"+version = "0.51.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"+dependencies = [+ "anyhow",+ "heck",+ "indexmap 2.12.1",+ "prettyplease",+ "syn 2.0.98",+ "wasm-metadata",+ "wit-bindgen-core",+ "wit-component",+]++[[package]]+name = "wit-bindgen-rust-macro"+version = "0.51.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"+dependencies = [+ "anyhow",+ "prettyplease",+ "proc-macro2",+ "quote",+ "syn 2.0.98",+ "wit-bindgen-core",+ "wit-bindgen-rust",+]++[[package]]+name = "wit-component"+version = "0.244.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"+dependencies = [+ "anyhow",+ "bitflags 2.8.0",+ "indexmap 2.12.1",+ "log",+ "serde",+ "serde_derive",+ "serde_json",+ "wasm-encoder",+ "wasm-metadata",+ "wasmparser",+ "wit-parser",+]++[[package]]+name = "wit-parser"+version = "0.244.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"+dependencies = [+ "anyhow",+ "id-arena",+ "indexmap 2.12.1",+ "log",+ "semver",+ "serde",+ "serde_derive",+ "serde_json",+ "unicode-xid",+ "wasmparser",+]+[[package]]name = "worker_trigger"version = "0.1.0"diff --git a/rust/cloud-storage/ai/src/openai_toolset.rs b/rust/cloud-storage/ai/src/openai_toolset.rsindex 351ee8ab9c..c4aa95bc20 100644--- a/rust/cloud-storage/ai/src/openai_toolset.rs+++ b/rust/cloud-storage/ai/src/openai_toolset.rs@@ -14,7 +14,7 @@ pub fn tool_object_to_chat_completion_tool<T>(value: &ToolObject<T>) -> ChatCompfunction: FunctionObject {name: value.name.clone(),description: Some(value.description.clone()),- parameters: Some(value.input_schema.clone()),+ parameters: Some(serde_json::Value::Object(value.input_schema.clone())),strict: Some(true),},}diff --git a/rust/cloud-storage/ai_toolset/src/schema/generate.rs b/rust/cloud-storage/ai_toolset/src/schema/generate.rsindex e052655e88..0fecb16a9e 100644--- a/rust/cloud-storage/ai_toolset/src/schema/generate.rs+++ b/rust/cloud-storage/ai_toolset/src/schema/generate.rs@@ -52,7 +52,7 @@ impl<Context> ToolSchemaGenerator for AsyncToolSet<Context> {.iter().map(|(name, tool_object)| ToolSchema {name: name.clone(),- input_schema: tool_object.input_schema.clone(),+ input_schema: serde_json::Value::Object(tool_object.input_schema.clone()),output_schema: tool_object.output_schema.clone(),}).collect();diff --git a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/object.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/object.rsindex 01b0f4749f..0de32b3e25 100644--- a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/object.rs+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/object.rs@@ -1,4 +1,5 @@use serde_json::Error as JsonError;+use serde_json::Map;use serde_json::Value;use thiserror::Error;@@ -8,7 +9,7 @@ use thiserror::Error;/// it to be invoked with JSON input at runtime.pub struct ToolObject<T> {/// The JSON schema describing the tool's input parameters.- pub input_schema: Value,+ pub input_schema: Map<String, Value>,/// The JSON schema describing the tool's output.pub output_schema: Value,/// A human-readable description of what the tool does.@@ -37,4 +38,7 @@ pub enum ValidationError {/// The schema contains `oneOf` which is not supported for AI tools.#[error("schema must not have oneOf set. Do not use descriptions or /// on enum types.")]OneOf,+ /// Schema must be a serde_json::Value::Object+ #[error("schema must be a serde_json::Value::Object")]+ ExpectedObject,}diff --git a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rsindex 14db8d89ad..7de3514ce1 100644--- a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs@@ -156,6 +156,9 @@ wherelet (name, description) = validate_tool_schema(&input_schema)?;let input_schema_json =serde_json::to_value(input_schema).map_err(ValidationError::JsonSerialization)?;+ let serde_json::Value::Object(input_schema_json) = input_schema_json else {+ return Err(ValidationError::ExpectedObject);+ };let deserializer = Box::new(|data: &serde_json::Value| {serde_json::from_value::<T>(data.clone()).map(|tool| {diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex c65dc43a4d..9070c0f14e 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -21,6 +21,10 @@ path = "src/openapi.rs"name = "document_cognition_service_models"path = "src/models_bin.rs"+[[bin]]+name = "mcp_server"+path = "src/bin/mcp_server.rs"+[features]local = []local_auth = ["macro_middleware/local_auth"]@@ -58,7 +62,9 @@ doppleganger = { workspace = true }email = { path = "../email", features = ["outbound"] }email_service_client = { path = "../email_service_client" }frecency = { path = "../frecency", features = ["outbound", "postgres"] }+fusionauth = { path = "../fusionauth" }futures = { workspace = true }+http = { workspace = true }http-body-util = { workspace = true }last_online_tracker = { path = "../last_online_tracker" }lazy_static = { workspace = true }@@ -88,6 +94,7 @@ models_opensearch = { path = "../models_opensearch" }models_permissions = { path = "../models_permissions" }regex = { workspace = true }reqwest.workspace = true+rmcp = { version = "1.2.0", features = ["transport-streamable-http-server"] }schemars = { workspace = true }scribe = { path = "../scribe", features = ["channel",@@ -100,6 +107,7 @@ search_service_client = { path = "../search_service_client" }secretsmanager_client = { path = "../secretsmanager_client" }serde = { workspace = true }serde_json = { workspace = true }+sha2 = { workspace = true }soup = { path = "../soup", features = ["outbound"] }sqlx = { workspace = true }sqs_client = { path = "../sqs_client", default-features = false, features = [@@ -127,6 +135,8 @@ tracing = { workspace = true }unfurl_service = { path = "../unfurl_service" }utoipa = { workspace = true, features = ["axum_extras", "chrono"] }utoipa-swagger-ui = { workspace = true, features = ["axum"] }+url = { workspace = true }+urlencoding = { workspace = true }uuid = { workspace = true }[dev-dependencies]diff --git a/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs b/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rsnew file mode 100644index 0000000000..b7e2353c89--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs@@ -0,0 +1,368 @@+//! MCP server binary that serves the DCS AI toolset over HTTP.+//!+//! This binary spins up a Streamable HTTP MCP server exposing the same+//! tools that are available in the DCS chat/stream API, with OAuth 2.1+//! authentication backed by FusionAuth.++use ai_tools::{NoOpConnectionService, NoOpTaskProperties, ToolServiceContext};+use anyhow::Context;+use comms::domain::service::ChannelServiceImpl;+use comms::outbound::postgres::comms_repo::PgCommsRepo;+use comms::outbound::postgres::user_repo::PgUserRepo;+use dashmap::DashMap;+use document_cognition_service::mcp_oauth::{+ mcp_router, state::OAuthState, tool_service::AuthenticatedToolService,+};+use document_cognition_service_client::DocumentCognitionServiceClient;+use document_storage_service_client::DocumentStorageServiceClient;+use documents::{+ domain::{models::CloudFrontConfig, service::DocumentServiceImpl},+ inbound::toolset::DocumentToolContext,+ outbound::{pg_document_repo::PgDocumentRepo, s3_upload_url::S3UploadUrlAdapter},+};+use email::domain::service::EmailServiceImpl;+use email::outbound::EmailPgRepo;+use email_service_client::{EmailServiceClient, EmailServiceClientExternal};+use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};+use frecency::domain::services::FrecencyQueryServiceImpl;+use frecency::outbound::postgres::FrecencyPgStorage;+use macro_auth::middleware::decode_jwt::JwtValidationArgs;+use macro_entrypoint::MacroEntrypoint;+use macro_env_var::env_var;+use macro_middleware::auth::internal_access::InternalApiSecretKey;+use rmcp::transport::streamable_http_server::{+ StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,+};+use scribe::{ScribeClient, document::DocumentClient};+use search_service_client::SearchServiceClient;+use secretsmanager_client::SecretManager;+use soup::domain::service::SoupImpl;+use soup::outbound::pg_soup_repo::PgSoupRepo;+use sqlx::postgres::PgPoolOptions;+use std::sync::Arc;+use sync_service_client::SyncServiceClient;++env_var!(+ struct McpEnvVars {+ DatabaseUrl,+ DocumentStorageServiceUrl,+ SyncServiceUrl,+ SyncServiceAuthKey,+ LexicalServiceUrl,+ EmailServiceUrl,+ StaticFileServiceUrl,+ DocumentStorageBucket,+ DocxDocumentUploadBucket,+ DocumentStorageServiceCloudfrontDistributionUrl,+ DocumentStorageServiceCloudfrontSignerPublicKeyId,+ DocumentStorageServiceCloudfrontSignerPrivateKeySecretName,+ McpPublicUrl,+ FusionauthBaseUrl,+ FusionauthClientId,+ FusionauthTenantId,+ FusionauthApiKeySecretKey,+ GoogleClientId,+ GoogleClientSecretKey,+ }+);++fn is_local() -> bool {+ matches!(+ macro_env::Environment::new_or_prod(),+ macro_env::Environment::Local+ )+}++#[tokio::main]+#[tracing::instrument(err)]+async fn main() -> anyhow::Result<()> {+ MacroEntrypoint::default().init();++ let env_vars = McpEnvVars::new().context("failed to load environment variables")?;++ // FusionAuth client secret uses a different env var name in local vs deployed+ let fusionauth_client_secret_env = if is_local() {+ std::env::var("FUSIONAUTH_CLIENT_SECRET")+ .context("FUSIONAUTH_CLIENT_SECRET must be provided")?+ } else {+ std::env::var("FUSIONAUTH_CLIENT_SECRET_KEY")+ .context("FUSIONAUTH_CLIENT_SECRET_KEY must be provided")?+ };++ let db = PgPoolOptions::new()+ .min_connections(3)+ .max_connections(10)+ .connect(&env_vars.database_url)+ .await+ .context("failed to connect to macrodb")?;++ tracing::info!("initialized db connection");++ let macro_env = macro_env::Environment::new_or_prod();+ let aws_config = macro_aws_config::get_macro_aws_config().await;++ let secretsmanager_client = secretsmanager_client::SecretsManager::new(+ aws_sdk_secretsmanager::Client::new(&aws_config),+ );++ // JWT validation args (reads JWT_SECRET_KEY, AUDIENCE, ISSUER, etc. from env)+ let jwt_args = JwtValidationArgs::new_with_secret_manager(macro_env, &secretsmanager_client)+ .await+ .context("failed to initialize JWT validation args")?;++ let internal_auth_key = secretsmanager_client::LocalOrRemoteSecret::Local(+ InternalApiSecretKey::new().context("failed to create internal auth key")?,+ );++ let dss_url: String = env_vars.document_storage_service_url.as_ref().to_owned();++ let document_storage_client =+ DocumentStorageServiceClient::new(internal_auth_key.as_ref().to_string(), dss_url.clone());++ let comms_service_client = comms_service_client::CommsServiceClient::new(dss_url.clone());++ let sync_service_auth_key = if is_local() {+ env_vars.sync_service_auth_key.as_ref().to_owned()+ } else {+ secretsmanager_client+ .get_secret_value(&env_vars.sync_service_auth_key)+ .await+ .context("failed to get sync service auth key from secrets manager")?+ .to_string()+ };++ let search_service_client =+ SearchServiceClient::new(internal_auth_key.as_ref().to_string(), dss_url);++ let lexical_client = Arc::new(lexical_client::LexicalClient::new(+ sync_service_auth_key.clone(),+ env_vars.lexical_service_url.as_ref().to_owned(),+ ));++ let email_service_client = Arc::new(EmailServiceClient::new(+ internal_auth_key.as_ref().to_string(),+ env_vars.email_service_url.as_ref().to_owned(),+ ));++ // DCS URL for scribe loopback — just use localhost on port 8080+ let dcs_url = std::env::var("DOCUMENT_COGNITION_SERVICE_URL")+ .unwrap_or_else(|_| "http://127.0.0.1:8080".to_string());+ let document_cognition_service_client = Arc::new(DocumentCognitionServiceClient::new(+ internal_auth_key.as_ref().to_string(),+ dcs_url,+ ));++ let static_file_service_client =+ Arc::new(static_file_service_client::StaticFileServiceClient::new(+ internal_auth_key.as_ref().to_string(),+ env_vars.static_file_service_url.as_ref().to_owned(),+ ));++ // Build soup service+ let frecency_storage = FrecencyPgStorage::new(db.clone());+ let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());+ let email_service = EmailServiceImpl::new(+ EmailPgRepo::new(db.clone()),+ frecency_service.clone(),+ email::domain::ports::NoOpEnqueuer,+ email::domain::ports::NoOpGmailLabelModifier,+ 0,+ );+ let channels_service = ChannelServiceImpl::new(+ PgCommsRepo { pool: db.clone() },+ PgUserRepo::new(db.clone()),+ frecency_storage,+ );+ let soup_service = Arc::new(SoupImpl::new(+ PgSoupRepo::new(db.clone()),+ frecency_service,+ email_service,+ channels_service,+ ));++ // Build document tool context+ let s3_client = macro_aws_config::s3_client().await;+ let s3_upload_adapter = S3UploadUrlAdapter::new(+ s3_client,+ env_vars.document_storage_bucket.as_ref(),+ env_vars.docx_document_upload_bucket.as_ref(),+ );+ let document_repo = PgDocumentRepo::new(db.clone());+ let cloudfront_private_key = if is_local() {+ env_vars+ .document_storage_service_cloudfront_signer_private_key_secret_name+ .as_ref()+ .to_owned()+ } else {+ secretsmanager_client+ .get_secret_value(+ &env_vars.document_storage_service_cloudfront_signer_private_key_secret_name,+ )+ .await+ .context("failed to get CloudFront signer private key from secrets manager")?+ .to_string()+ };+ let cloudfront_config = CloudFrontConfig {+ distribution_url: env_vars+ .document_storage_service_cloudfront_distribution_url+ .as_ref()+ .to_owned(),+ signer_public_key_id: env_vars+ .document_storage_service_cloudfront_signer_public_key_id+ .as_ref()+ .to_owned(),+ signer_private_key: cloudfront_private_key,+ presigned_url_expiry_seconds: 3600,+ browser_cache_expiry_seconds: 86400,+ };+ let sync_service_url: String = env_vars.sync_service_url.as_ref().to_owned();+ let sync_service_client =+ SyncServiceClient::new(sync_service_auth_key.clone(), sync_service_url.clone());+ let document_service = DocumentServiceImpl::new(+ document_repo,+ cloudfront_config,+ sync_service_client.clone(),+ s3_upload_adapter,+ NoOpTaskProperties,+ NoOpConnectionService,+ );+ let entity_access_service = EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone()));+ let lexical_client_for_tools = (*lexical_client).clone();+ let document_tool_context = DocumentToolContext::new(+ document_service,+ entity_access_service,+ lexical_client_for_tools,+ );++ // Build the ToolServiceContext+ let tool_context = ToolServiceContext {+ email_service_client: Arc::new(EmailServiceClientExternal::new(+ email_service_client.url().to_owned(),+ )),+ search_service_client: Arc::new(search_service_client),+ scribe: Arc::new(+ ScribeClient::new()+ .with_document_client(+ DocumentClient::builder()+ .with_dss_client(document_storage_client)+ .with_lexical_client(lexical_client)+ .with_sync_service_client(SyncServiceClient::new(+ sync_service_auth_key,+ sync_service_url,+ ))+ .with_macro_db(db.clone())+ .build(),+ )+ .with_channel_client_and_db(comms_service_client, db.clone())+ .with_dcs_client(document_cognition_service_client)+ .with_email_client(email_service_client)+ .with_static_file_client(static_file_service_client),+ ),+ soup_service,+ document_tool_context,+ };++ tracing::info!("initialized tool context");++ // Create the MCP service with authenticated tool handler+ let mcp_service = StreamableHttpService::new(+ move || {+ let tools = ai_tools::all_tools();+ Ok(AuthenticatedToolService::new(+ tools.toolset,+ tool_context.clone(),+ ))+ },+ Arc::new(LocalSessionManager::default()),+ StreamableHttpServerConfig::default(),+ );++ // Build FusionAuth client for the MCP OAuth flow.+ // The oauth_redirect_uri points to the MCP server's own callback endpoint.+ let mcp_public_url: String = env_vars.mcp_public_url.as_ref().to_owned();+ let mcp_oauth_redirect_uri = format!("{mcp_public_url}/oauth/callback");++ let fusionauth_api_key = if is_local() {+ env_vars.fusionauth_api_key_secret_key.as_ref().to_owned()+ } else {+ secretsmanager_client+ .get_secret_value(&env_vars.fusionauth_api_key_secret_key)+ .await+ .context("failed to get FusionAuth API key")?+ .to_string()+ };++ let fusionauth_client_secret = if is_local() {+ fusionauth_client_secret_env+ } else {+ secretsmanager_client+ .get_secret_value(&fusionauth_client_secret_env)+ .await+ .context("failed to get FusionAuth client secret")?+ .to_string()+ };++ let google_client_secret = if is_local() {+ env_vars.google_client_secret_key.as_ref().to_owned()+ } else {+ secretsmanager_client+ .get_secret_value(&env_vars.google_client_secret_key)+ .await+ .context("failed to get Google client secret")?+ .to_string()+ };++ let fusionauth_client = fusionauth::FusionAuthClient::new(+ env_vars.fusionauth_tenant_id.as_ref().to_owned(),+ fusionauth_api_key,+ env_vars.fusionauth_client_id.as_ref().to_owned(),+ fusionauth_client_secret,+ env_vars.fusionauth_base_url.as_ref().to_owned(),+ mcp_oauth_redirect_uri,+ env_vars.google_client_id.as_ref().to_owned(),+ google_client_secret,+ );++ // Resolve the Google IDP ID at startup so we don't need it as an env var.+ let google_idp_id = fusionauth_client+ .get_identity_provider_id_by_name("google")+ .await+ .context("failed to look up Google identity provider in FusionAuth")?;+ tracing::info!(%google_idp_id, "resolved Google IDP ID from FusionAuth");++ // Build OAuth state+ let oauth_state = OAuthState {+ pending: Arc::new(DashMap::new()),+ codes: Arc::new(DashMap::new()),+ jwt_args: jwt_args.clone(),+ fusionauth_client: Arc::new(fusionauth_client),+ google_idp_id,+ mcp_public_url: mcp_public_url.clone(),+ };++ // Spawn background cleanup for expired OAuth entries+ let cleanup_state = oauth_state.clone();+ tokio::spawn(async move {+ let mut interval = tokio::time::interval(std::time::Duration::from_secs(60));+ loop {+ interval.tick().await;+ cleanup_state.cleanup_expired();+ }+ });++ let app = mcp_router(oauth_state, jwt_args, mcp_service);++ let port = std::env::var("PORT").unwrap_or_else(|_| "8090".to_string());+ let addr = format!("0.0.0.0:{port}");+ let listener = tokio::net::TcpListener::bind(&addr)+ .await+ .context("failed to bind MCP server")?;++ tracing::info!("MCP server listening on http://{addr}/mcp");++ axum::serve(listener, app)+ .await+ .context("MCP server error")?;++ Ok(())+}diff --git a/rust/cloud-storage/document_cognition_service/src/lib.rs b/rust/cloud-storage/document_cognition_service/src/lib.rsnew file mode 100644index 0000000000..39633b9812--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/lib.rs@@ -0,0 +1,2 @@+/// OAuth 2.1 proxy for the MCP server.+pub mod mcp_oauth;diff --git a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/handlers.rs b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/handlers.rsnew file mode 100644index 0000000000..c66b94ca78--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/handlers.rs@@ -0,0 +1,323 @@+use axum::{+ extract::{Query, State},+ response::{IntoResponse, Json, Redirect, Response},+};+use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use std::time::{Duration, Instant};++use super::state::OAuthState;++// ── 1. Discovery ────────────────────────────────────────────────────────++/// `GET /.well-known/oauth-authorization-server`+pub async fn metadata(State(state): State<OAuthState>) -> Json<serde_json::Value> {+ tracing::debug!("oauth-authorization-server metadata requested");+ let base = &state.mcp_public_url;+ Json(serde_json::json!({+ "issuer": base,+ "authorization_endpoint": format!("{base}/authorize"),+ "token_endpoint": format!("{base}/token"),+ "registration_endpoint": format!("{base}/register"),+ "response_types_supported": ["code"],+ "grant_types_supported": ["authorization_code"],+ "code_challenge_methods_supported": ["S256"],+ }))+}++// ── 1b. Dynamic Client Registration (RFC 7591) ─────────────────────────++/// `POST /register` — accepts a dynamic client registration request and returns+/// a new client_id. Since we proxy all auth through FusionAuth and use PKCE,+/// we don't need real client credentials — we just mint a unique client_id.+pub async fn register(axum::Json(body): axum::Json<serde_json::Value>) -> Response {+ let client_id = uuid::Uuid::new_v4().to_string();+ let client_name = body+ .get("client_name")+ .and_then(|v| v.as_str())+ .unwrap_or("mcp-client");++ tracing::info!(%client_id, %client_name, "dynamic client registration");++ Json(serde_json::json!({+ "client_id": client_id,+ "client_name": client_name,+ "redirect_uris": body.get("redirect_uris").cloned().unwrap_or(serde_json::json!([])),+ "grant_types": ["authorization_code"],+ "response_types": ["code"],+ "token_endpoint_auth_method": "none",+ }))+ .into_response()+}++// ── 2. Authorize ────────────────────────────────────────────────────────++#[derive(Deserialize)]+pub struct AuthorizeParams {+ response_type: String,+ #[allow(dead_code)]+ client_id: String,+ redirect_uri: String,+ state: String,+ code_challenge: String,+ code_challenge_method: String,+ #[serde(default)]+ #[allow(dead_code)]+ scope: Option<String>,+}++/// Returns `true` if the redirect URI is acceptable.+///+/// We allow loopback addresses (with any port) and `http://localhost` variants,+/// which covers MCP clients like Claude Desktop that spin up a local callback+/// server. All other origins are rejected to prevent open-redirect attacks.+fn is_allowed_redirect_uri(uri: &str) -> bool {+ let Ok(parsed) = url::Url::parse(uri) else {+ return false;+ };++ matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))+}++/// `GET /authorize` — validates params, stores the pending flow, then redirects+/// to FusionAuth's `/oauth2/authorize` endpoint with the Google IDP hint. After+/// the user logs in, FusionAuth redirects back to our `/oauth/callback` with an+/// authorization code.+pub async fn authorize(+ State(oauth): State<OAuthState>,+ Query(params): Query<AuthorizeParams>,+) -> Response {+ if params.response_type != "code" {+ return (+ axum::http::StatusCode::BAD_REQUEST,+ "unsupported response_type",+ )+ .into_response();+ }+ if params.code_challenge_method != "S256" {+ return (+ axum::http::StatusCode::BAD_REQUEST,+ "unsupported code_challenge_method",+ )+ .into_response();+ }+ if !is_allowed_redirect_uri(¶ms.redirect_uri) {+ return (+ axum::http::StatusCode::BAD_REQUEST,+ "redirect_uri must be a loopback address",+ )+ .into_response();+ }++ // Generate a session ID to correlate the callback.+ let session_id = uuid::Uuid::new_v4().to_string();+ tracing::info!(%session_id, "starting OAuth authorize flow");++ oauth.pending.insert(+ session_id.clone(),+ super::state::PendingAuthFlow {+ code_challenge: params.code_challenge,+ client_state: params.state,+ client_redirect_uri: params.redirect_uri,+ expires_at: Instant::now() + Duration::from_secs(600),+ },+ );++ // Build the FusionAuth authorize URL with the Google IDP hint.+ // The session_id is threaded through FusionAuth's `state` parameter so we+ // can correlate the callback.+ let fusionauth_url = match oauth.fusionauth_client.construct_oauth2_authorize_url(+ &oauth.google_idp_id,+ None,+ Some(session_id),+ ) {+ Ok(url) => url,+ Err(e) => {+ tracing::error!(error=?e, "failed to construct FusionAuth authorize URL");+ return (+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,+ "failed to construct authorize URL",+ )+ .into_response();+ }+ };++ Redirect::temporary(&fusionauth_url).into_response()+}++// ── 3. OAuth callback (FusionAuth → us via redirect) ─────────────────────++#[derive(Deserialize)]+pub struct CallbackParams {+ /// Authorization code from FusionAuth.+ code: String,+ /// Our session ID, threaded through FusionAuth's `state` parameter.+ state: Option<String>,+}++/// `GET /oauth/callback` — FusionAuth redirects here after the user logs in+/// via Google. The `code` query param is a FusionAuth authorization code that+/// we exchange for a JWT by calling FusionAuth's `POST /oauth2/token` endpoint.+pub async fn oauth_callback(+ State(oauth): State<OAuthState>,+ Query(params): Query<CallbackParams>,+) -> Response {+ // FusionAuth passes state back as a JSON string (since construct_oauth2_authorize_url+ // serializes it with serde_json). Strip the surrounding quotes.+ let session_id = match ¶ms.state {+ Some(s) => s.trim_matches('"').to_string(),+ None => {+ tracing::warn!("no state parameter in FusionAuth callback");+ return (+ axum::http::StatusCode::BAD_REQUEST,+ "missing state parameter",+ )+ .into_response();+ }+ };+ tracing::info!(%session_id, pending_count = oauth.pending.len(), "oauth callback received");++ // Look up the pending flow.+ let pending = match oauth.pending.remove(&session_id) {+ Some((_, p)) => p,+ None => {+ tracing::warn!(%session_id, "no pending flow found for session");+ return (+ axum::http::StatusCode::BAD_REQUEST,+ "unknown or expired session",+ )+ .into_response();+ }+ };++ // Exchange the FusionAuth authorization code for a JWT via FusionAuth's+ // POST /oauth2/token endpoint.+ let (access_token, _refresh_token) = match oauth+ .fusionauth_client+ .complete_authorization_code_grant(¶ms.code)+ .await+ {+ Ok(tokens) => tokens,+ Err(e) => {+ tracing::error!(error=?e, "FusionAuth authorization code grant failed");+ return (+ axum::http::StatusCode::BAD_GATEWAY,+ "authorization code exchange failed",+ )+ .into_response();+ }+ };++ // Issue our own authorization code, storing the validated JWT.+ let our_code = uuid::Uuid::new_v4().to_string();+ oauth.codes.insert(+ our_code.clone(),+ super::state::IssuedCode {+ access_token,+ code_challenge: pending.code_challenge,+ redirect_uri: pending.client_redirect_uri.clone(),+ expires_at: Instant::now() + Duration::from_secs(300),+ },+ );++ // Redirect back to the client (Claude) with our code and the original state.+ let redirect_url = format!(+ "{}?code={}&state={}",+ pending.client_redirect_uri,+ urlencoding::encode(&our_code),+ urlencoding::encode(&pending.client_state),+ );++ Redirect::temporary(&redirect_url).into_response()+}++// ── 4. Token exchange ───────────────────────────────────────────────────++#[derive(Deserialize)]+pub struct TokenParams {+ grant_type: String,+ code: String,+ #[serde(default)]+ code_verifier: Option<String>,+ #[serde(default)]+ redirect_uri: Option<String>,+ #[serde(default)]+ #[allow(dead_code)]+ client_id: Option<String>,+}++#[derive(Serialize)]+struct TokenResponse {+ access_token: String,+ token_type: &'static str,+}++/// `POST /token` — client exchanges our authorization code for an access token.+pub async fn token(+ State(oauth): State<OAuthState>,+ axum::Form(params): axum::Form<TokenParams>,+) -> Response {+ if params.grant_type != "authorization_code" {+ return (+ axum::http::StatusCode::BAD_REQUEST,+ "unsupported grant_type",+ )+ .into_response();+ }++ let issued = match oauth.codes.remove(¶ms.code) {+ Some((_, c)) => c,+ None => {+ return (+ axum::http::StatusCode::BAD_REQUEST,+ "invalid or expired code",+ )+ .into_response();+ }+ };++ if issued.expires_at < Instant::now() {+ return (axum::http::StatusCode::BAD_REQUEST, "code expired").into_response();+ }++ // OAuth 2.1 §4.1.3: if redirect_uri was in the authorization request,+ // it must match exactly in the token request.+ match ¶ms.redirect_uri {+ Some(uri) if *uri != issued.redirect_uri => {+ return (axum::http::StatusCode::BAD_REQUEST, "redirect_uri mismatch").into_response();+ }+ None => {+ return (axum::http::StatusCode::BAD_REQUEST, "redirect_uri required").into_response();+ }+ _ => {}+ }++ // Validate PKCE: BASE64URL(SHA256(code_verifier)) must equal code_challenge.+ match params.code_verifier {+ Some(verifier) => {+ let digest = Sha256::digest(verifier.as_bytes());+ let computed = URL_SAFE_NO_PAD.encode(digest);+ if computed != issued.code_challenge {+ return (+ axum::http::StatusCode::BAD_REQUEST,+ "PKCE verification failed",+ )+ .into_response();+ }+ }+ None => {+ return (+ axum::http::StatusCode::BAD_REQUEST,+ "code_verifier required",+ )+ .into_response();+ }+ }++ Json(TokenResponse {+ access_token: issued.access_token,+ token_type: "Bearer",+ })+ .into_response()+}diff --git a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/middleware.rs b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/middleware.rsnew file mode 100644index 0000000000..6c599deddf--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/middleware.rs@@ -0,0 +1,54 @@+use axum::{+ body::Body,+ http::{Request, StatusCode},+ response::IntoResponse,+};+use macro_auth::middleware::decode_jwt::{JwtToken, JwtValidationArgs, handler};++/// Validated user identity extracted from the Bearer token.+#[derive(Clone, Debug)]+pub struct McpUserIdentity {+ /// The macro user id (e.g. `macro|[email protected]`).+ pub user_id: String,+ /// The raw JWT string (some downstream code still needs it).+ pub jwt: String,+}++/// Axum middleware that validates the `Authorization: Bearer <token>` header+/// and inserts an [`McpUserIdentity`] into request extensions.+pub async fn validate_bearer(+ axum::extract::State(jwt_args): axum::extract::State<JwtValidationArgs>,+ mut request: Request<Body>,+ next: axum::middleware::Next,+) -> axum::response::Response {+ let token = request+ .headers()+ .get(axum::http::header::AUTHORIZATION)+ .and_then(|v| v.to_str().ok())+ .and_then(|v| v.strip_prefix("Bearer "))+ .map(|s| s.to_owned());++ let Some(token) = token else {+ return StatusCode::UNAUTHORIZED.into_response();+ };++ let jwt_token = match handler(&jwt_args, &token) {+ Ok(t) => t,+ Err(e) => {+ tracing::warn!(error=?e, "MCP bearer token validation failed");+ return StatusCode::UNAUTHORIZED.into_response();+ }+ };++ let user_id = match &jwt_token {+ JwtToken::MacroAccessToken(t) => t.macro_user_id.clone(),+ JwtToken::MacroApiToken(t) => t.macro_user_id.clone(),+ };++ request.extensions_mut().insert(McpUserIdentity {+ user_id,+ jwt: token,+ });++ next.run(request).await+}diff --git a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/mod.rs b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/mod.rsnew file mode 100644index 0000000000..f6b9fa2f06--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/mod.rs@@ -0,0 +1,55 @@+//! OAuth 2.1 proxy for the MCP server.+//!+//! Exposes OAuth endpoints that Claude talks to, proxying the actual+//! authentication to FusionAuth behind the scenes.++pub mod handlers;+pub mod middleware;+pub mod state;+pub mod tool_service;++use axum::{Router, middleware as axum_mw, routing};+use macro_auth::middleware::decode_jwt::JwtValidationArgs;+use state::OAuthState;++/// Health check handler for ALB.+async fn health() -> &'static str {+ "ok"+}++/// Build the complete router for the MCP server: OAuth routes (unauthenticated)+/// merged with the `/mcp` route (Bearer-authenticated).+pub fn mcp_router<S>(oauth_state: OAuthState, jwt_args: JwtValidationArgs, mcp_service: S) -> Router+where+ S: tower::Service<axum::http::Request<axum::body::Body>, Error = std::convert::Infallible>+ + Clone+ + Send+ + Sync+ + 'static,+ S::Response: axum::response::IntoResponse,+ S::Future: Send + 'static,+{+ // OAuth routes — no auth required.+ let oauth_routes = Router::new()+ .route("/health", routing::get(health))+ .route(+ "/.well-known/oauth-authorization-server",+ routing::get(handlers::metadata),+ )+ .route("/authorize", routing::get(handlers::authorize))+ .route("/register", routing::post(handlers::register))+ .route("/oauth/callback", routing::get(handlers::oauth_callback))+ .route("/token", routing::post(handlers::token))+ .with_state(oauth_state);++ // MCP route — protected by Bearer token middleware.+ let mcp_route =+ Router::new()+ .nest_service("/mcp", mcp_service)+ .layer(axum_mw::from_fn_with_state(+ jwt_args,+ middleware::validate_bearer,+ ));++ oauth_routes.merge(mcp_route)+}diff --git a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/state.rs b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/state.rsnew file mode 100644index 0000000000..5ad92b68b2--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/state.rs@@ -0,0 +1,60 @@+use dashmap::DashMap;+use macro_auth::middleware::decode_jwt::JwtValidationArgs;+use std::sync::Arc;+use std::time::Instant;++/// A pending OAuth authorization flow initiated by the client.+#[derive(Clone)]+pub struct PendingAuthFlow {+ /// PKCE S256 code challenge from the client.+ pub code_challenge: String,+ /// The client's original `state` parameter.+ pub client_state: String,+ /// Where to redirect back to the client with the authorization code.+ pub client_redirect_uri: String,+ /// When this flow expires (TTL ~10 min).+ pub expires_at: Instant,+}++/// An authorization code we issued, backed by a validated JWT.+#[derive(Clone)]+pub struct IssuedCode {+ /// The access token (JWT) obtained from FusionAuth.+ pub access_token: String,+ /// The original PKCE code challenge, for verification at token exchange.+ pub code_challenge: String,+ /// The `redirect_uri` used in the authorization request, for validation at+ /// token exchange per OAuth 2.1 §4.1.3.+ pub redirect_uri: String,+ /// When this code expires (TTL ~5 min).+ pub expires_at: Instant,+}++/// Shared state for the OAuth proxy.+///+/// The DashMaps are wrapped in `Arc` so that axum's state cloning shares the+/// same underlying maps across all handlers.+#[derive(Clone)]+pub struct OAuthState {+ /// Pending authorization flows, keyed by session ID.+ pub pending: Arc<DashMap<String, PendingAuthFlow>>,+ /// Issued authorization codes, keyed by the code string.+ pub codes: Arc<DashMap<String, IssuedCode>>,+ /// JWT validation args (shared with the `/mcp` Bearer middleware).+ pub jwt_args: JwtValidationArgs,+ /// FusionAuth client for OAuth2 authorization code grant.+ pub fusionauth_client: Arc<fusionauth::FusionAuthClient>,+ /// The Google identity provider ID in FusionAuth, used as `idp_hint`.+ pub google_idp_id: String,+ /// Externally-reachable URL of this MCP server (e.g. `http://localhost:8090`).+ pub mcp_public_url: String,+}++impl OAuthState {+ /// Remove expired entries from both maps.+ pub fn cleanup_expired(&self) {+ let now = Instant::now();+ self.pending.retain(|_, v| v.expires_at > now);+ self.codes.retain(|_, v| v.expires_at > now);+ }+}diff --git a/rust/cloud-storage/document_cognition_service/src/mcp_oauth/tool_service.rs b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/tool_service.rsnew file mode 100644index 0000000000..f3f2737807--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/mcp_oauth/tool_service.rs@@ -0,0 +1,129 @@+use ai_toolset::{AsyncToolSet, RequestContext};+use macro_user_id::user_id::MacroUserIdStr;+use rmcp::{+ handler::server::ServerHandler,+ model::{+ Content, ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerInfo, Tool,+ },+};+use std::sync::Arc;++use super::middleware::McpUserIdentity;++/// MCP server handler that extracts authenticated user identity from HTTP+/// request parts injected by rmcp's `StreamableHttpService`.+pub struct AuthenticatedToolService<Context> {+ toolset: AsyncToolSet<Context>,+ context: Context,+}++impl<Context> AuthenticatedToolService<Context> {+ /// Create a new authenticated tool service.+ pub fn new(toolset: AsyncToolSet<Context>, context: Context) -> Self {+ Self { toolset, context }+ }+}++impl<Context> ServerHandler for AuthenticatedToolService<Context>+where+ Context: Clone + Send + Sync + 'static,+{+ fn get_info(&self) -> ServerInfo {+ let mut info = ServerInfo::new(ServerCapabilities::builder().enable_tools().build());+ info.server_info = rmcp::model::Implementation::new(+ "macro-tools",+ env!("CARGO_PKG_VERSION"),+ )+ .with_title("Macro")+ .with_description(+ "Search, read, and create content across documents, emails, and messages in Macro.",+ );+ info.instructions = Some(+ "This server provides tools for interacting with a user's Macro workspace. \+ Use ContentSearch and NameSearch to find entities. \+ Use ReadContent, ReadMetadata, and ReadThread to read them. \+ Use CreateDocument to create new documents. \+ Use ListEntities to browse recent items."+ .into(),+ );+ info+ }++ async fn list_tools(+ &self,+ _request: Option<PaginatedRequestParams>,+ _context: rmcp::service::RequestContext<rmcp::RoleServer>,+ ) -> Result<ListToolsResult, rmcp::ErrorData> {+ let tools = self+ .toolset+ .tools+ .iter()+ .map(|(k, v)| {+ Tool::new(+ k.to_owned(),+ v.description.to_owned(),+ Arc::new(v.input_schema.clone()),+ )+ })+ .collect::<Vec<_>>();++ Ok(ListToolsResult {+ tools,+ ..Default::default()+ })+ }++ async fn call_tool(+ &self,+ request: rmcp::model::CallToolRequestParams,+ context: rmcp::service::RequestContext<rmcp::RoleServer>,+ ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {+ // Extract user identity from HTTP parts injected by rmcp.+ let identity = context+ .extensions+ .get::<http::request::Parts>()+ .and_then(|parts| parts.extensions.get::<McpUserIdentity>().cloned())+ .ok_or_else(|| {+ rmcp::ErrorData::internal_error("missing user identity — is auth configured?", None)+ })?;++ let user_id = MacroUserIdStr::try_from(identity.user_id.clone())+ .map_err(|e| rmcp::ErrorData::internal_error(format!("invalid user id: {e}"), None))?;++ #[allow(deprecated)]+ let request_context = RequestContext {+ jwt: Arc::new(identity.jwt.clone()),+ user_id: Arc::new(user_id),+ };++ let arguments = request+ .arguments+ .map(serde_json::Value::Object)+ .ok_or(rmcp::ErrorData::invalid_params("No params provided", None))?;++ let result = self+ .toolset+ .try_tool_call(+ self.context.clone(),+ request_context,+ &request.name,+ &arguments,+ )+ .await+ .map_err(|e| match e {+ ai_toolset::ToolSetError::Deserialization(e) => {+ rmcp::ErrorData::parse_error(e.to_string(), None)+ }+ ai_toolset::ToolSetError::NotFound(s) => {+ rmcp::ErrorData::resource_not_found(s, None)+ }+ })?;++ match result {+ Ok(good) => Ok(rmcp::model::CallToolResult::structured(good)),+ Err(bad) => Ok(rmcp::model::CallToolResult::error(vec![Content::text(+ bad.description,+ )])),+ }+ }+}diff --git a/test.md b/test.mdnew file mode 100644index 0000000000..73fdc55122--- /dev/null+++ b/test.md@@ -0,0 +1,5 @@+# Test File++Created by Claude (Opus 4.6)++**Time:** 2026-03-20, generated during a Claude Code session.