Skip to content

Conversation

@amikofalvy
Copy link
Collaborator

Summary

Fixes the authentication issue where MCP tool calls from the copilot chat were failing with "Invalid Token" errors. The root cause was that the auth middleware wasn't validating sessions via cookie headers, only via the Authorization header.

Changes

Auth Fix (Key Change)

  • agents-manage-api/src/middleware/auth.ts - Added cookie header validation to the auth middleware. Now checks x-forwarded-cookie and cookie headers for session validation alongside the Authorization header.

Header Forwarding Infrastructure

  • agents-run-api/src/routes/chatDataStream.ts - Extract and transform cookiex-forwarded-cookie for the /api/chat route
  • agents-run-api/src/routes/chat.ts - Same transformation for /v1/chat/completions route
  • agents-run-api/src/a2a/handlers.ts - Extract headers from incoming A2A requests and pass to task metadata
  • agents-run-api/src/a2a/types.ts - Added forwardedHeaders to A2ATaskMetadata type
  • agents-run-api/src/handlers/executionHandler.ts - Added forwardedHeaders param to pass headers to A2A client
  • agents-run-api/src/agents/generateTaskHandler.ts - Extract headers from task metadata and pass to Agent
  • agents-run-api/src/agents/Agent.ts - Merge forwarded headers into MCP config + include in cache key to prevent stale connections

MCP/SDK

  • agents-manage-api/src/routes/mcp.ts - Map x-forwarded-cookiecookie for downstream API calls + security comment
  • packages/agents-manage-mcp/src/hooks/header-forwarding-hook.ts - Simplified header forwarding hook

Security

  • packages/agents-core/src/utils/logger.ts - Added redaction for cookie and x-forwarded-cookie headers
  • agents-manage-ui/src/lib/logger.ts - Same header redaction

Flow

  1. Browser sends cookie header to Run API
  2. Run API transforms cookiex-forwarded-cookie and passes through A2A task metadata
  3. Agent passes forwarded headers to MCP client
  4. MCP client sends headers to Manage API /mcp endpoint
  5. Manage API /mcp maps x-forwarded-cookiecookie for SDK hook
  6. SDK hook applies cookie header to downstream API requests
  7. Auth middleware validates session via cookie header

Testing

Tested end-to-end with copilot chat - MCP tool calls now authenticate successfully using the user's browser session cookie.

- Add cookie header validation to auth middleware (x-forwarded-cookie and cookie)
- Forward user session headers through A2A task metadata
- Transform browser cookie header to x-forwarded-cookie for downstream forwarding
- Include forwarded headers in MCP client cache key to prevent stale connections
- Add header redaction for cookie and x-forwarded-cookie in loggers
- Add security comment about not using debugLogger with sensitive headers
@vercel
Copy link

vercel bot commented Jan 7, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
agents-manage-api Ready Ready Preview, Comment Jan 7, 2026 4:35am
agents-manage-ui Ready Ready Preview, Comment Jan 7, 2026 4:35am
agents-run-api Ready Ready Preview, Comment Jan 7, 2026 4:35am
1 Skipped Deployment
Project Deployment Review Updated (UTC)
agents-docs Skipped Skipped Jan 7, 2026 4:35am

@changeset-bot
Copy link

changeset-bot bot commented Jan 7, 2026

🦋 Changeset detected

Latest commit: c2fb299

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 9 packages
Name Type
@inkeep/agents-cli Patch
@inkeep/agents-core Patch
@inkeep/agents-manage-api Patch
@inkeep/agents-manage-ui Patch
@inkeep/agents-run-api Patch
@inkeep/agents-sdk Patch
@inkeep/create-agents Patch
@inkeep/ai-sdk-provider Patch
@inkeep/agents-manage-mcp Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@claude
Copy link

claude bot commented Jan 7, 2026

Claude finished @amikofalvy's task —— View job


🔍 Comprehensive Code Review Complete

I've conducted a thorough architectural and code quality review of this cookie header forwarding implementation. Here's my analysis:

Overview Assessment

This PR implements a comprehensive cookie header forwarding system to fix authentication issues with MCP tool calls from copilot chat. The implementation is well-structured and addresses a legitimate authentication gap.

Key Strengths ✅

1. Complete Flow Implementation

  • Properly implements end-to-end flow: Browser → Run API → A2A → Agent → MCP → Manage API → SDK
  • Consistent header transformation pattern (cookiex-forwarded-cookie) across all layers
  • Smart priority handling: explicit x-forwarded-cookie takes precedence over browser cookie

2. Security Considerations

  • Excellent security-conscious logging: cookies redacted in both packages/agents-core/src/utils/logger.ts:42-43 and agents-manage-ui/src/lib/logger.ts
  • Clear security comment in agents-manage-api/src/routes/mcp.ts:49 about not enabling debug logging
  • Proper header mapping without exposing sensitive data

3. Caching Strategy

  • Smart cache key strategy in Agent.ts includes forwarded headers hash to prevent cross-user session contamination
  • Prevents reusing connections created without cookies for requests that have them

Areas for Improvement 🔍

1. Type Safety & Consistency (Medium Priority)

// Current implementation uses generic Record<string, any>
metadata?: Record<string, any>

Recommendation: Consider defining a more specific type for A2A task metadata:

interface A2ATaskMetadata {
  blocking?: boolean;
  custom?: Record<string, string>;
  conversationId?: string;
  forwardedHeaders?: Record<string, string>;
  // ... other known properties
}

This would provide better type safety and make the forwarded headers pattern more explicit.

2. Error Handling & Edge Cases (Medium Priority)

The code doesn't handle several edge cases:

a) Header Size Limits:

// Consider adding validation
if (Object.keys(forwardedHeaders).length > 0) {
  const headerSize = JSON.stringify(forwardedHeaders).length;
  if (headerSize > MAX_HEADER_SIZE) {
    logger.warn('Forwarded headers exceed size limit, truncating');
    // Handle appropriately
  }
}

b) Malformed Headers: No validation for header content format or potential injection attacks.

c) Connection Failures: The auth middleware fallback logic could be more robust when session validation fails with forwarded cookies.

3. Documentation & Comments (Low Priority)

While the security comment in mcp.ts is excellent, consider adding:

  • JSDoc comments for the header transformation logic
  • Clear documentation about the header priority system
  • Flow diagrams in comments for complex authentication paths

4. Code Duplication (Low Priority)

The header extraction logic is duplicated across multiple files:

  • agents-run-api/src/routes/chatDataStream.ts:114-126
  • agents-run-api/src/routes/chat.ts (similar pattern)
  • agents-run-api/src/a2a/handlers.ts:93-106

Recommendation: Extract into a shared utility:

// utils/headerExtraction.ts
export function extractForwardedHeaders(request: HonoRequest): Record<string, string> {
  const forwardedHeaders: Record<string, string> = {};
  const xForwardedCookie = request.header('x-forwarded-cookie');
  const authorization = request.header('authorization');
  const cookie = request.header('cookie');
  
  // Priority: x-forwarded-cookie (explicit) > cookie (browser-sent)
  if (xForwardedCookie) {
    forwardedHeaders['x-forwarded-cookie'] = xForwardedCookie;
  } else if (cookie) {
    forwardedHeaders['x-forwarded-cookie'] = cookie;
  }
  if (authorization) forwardedHeaders.authorization = authorization;
  
  return forwardedHeaders;
}

5. Testing Considerations (Medium Priority)

This implementation would benefit from:

  • Unit tests for header transformation logic
  • Integration tests for the complete authentication flow
  • Edge case tests for malformed/oversized headers
  • Cache invalidation tests for the Agent connection caching

Architectural Assessment 🏗️

Excellent Design Patterns:

  • Follows the established pattern of transforming headers at boundaries
  • Maintains separation of concerns across service layers
  • Uses existing infrastructure (SDK hooks, middleware) appropriately

Future Considerations:

  • This approach scales well for additional header forwarding needs
  • The pattern could be extended for other authentication mechanisms
  • Consider whether this precedent should be documented as a standard pattern

Security Review 🔒

Strong security practices:

  • Headers properly redacted from logs
  • No exposure of sensitive auth data in debug output
  • Appropriate boundary enforcement between services

Minor security note: Consider adding header sanitization to prevent potential header injection attacks, especially if these headers might be used in downstream HTTP requests.

Final Assessment

This is a well-implemented solution that addresses a legitimate authentication gap. The code follows good architectural patterns and demonstrates security awareness. The main improvements are around code organization (reducing duplication), type safety, and comprehensive error handling.

Recommendation: Approve with minor improvements - The implementation is solid and production-ready, with suggested improvements being optimization opportunities rather than blocking issues.


@amikofalvy amikofalvy merged commit f58f9e4 into main Jan 7, 2026
2 of 3 checks passed
@amikofalvy amikofalvy deleted the fix/cookie-header-forwarding-auth branch January 7, 2026 04:33
@vercel vercel bot temporarily deployed to Preview – agents-docs January 7, 2026 04:33 Inactive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants