Skip to content

[Feature]: Support passing custom context from InboundMessage to RuntimeContext #1966

Closed

Description

@BeginnerCong

When building a multi-tenant application with AgentScope, we need to pass business-specific parameters (like modelConfigId, datasourceId, tenantId) from the Controller layer all the way down to the Middleware/Tool layer via RuntimeContext.

Currently, InboundMessage has no mechanism to carry custom key-value pairs, and ChannelRouter.buildContext only puts agentId into MsgContext.extra. This forces us to use ConcurrentHashMap with userId as the key to simulate context passing:

// Workaround: Store in ConcurrentHashMap before dispatch
modelContext.put(userId, modelConfigId);
datasourceContext.put(userId, datasourceId);

// Workaround: Retrieve in Gateway
private void attachModelContext(RuntimeContext.Builder builder, String userId) {
    String modelConfigId = modelContext.resolve(userId);
    if (modelConfigId != null) {
        builder.put("modelConfigId", modelConfigId);
    }
}

// Workaround: Clean up after dispatch
modelContext.remove(userId);
datasourceContext.remove(userId);

This approach has several issues:

  1. Manual lifecycle management - Must remember to put before and remove after each call
  2. Memory leak risk - If remove is missed in error paths, entries accumulate
  3. Thread safety concerns - put and remove are not atomic
  4. Unclear data flow - Context goes through an intermediate ConcurrentHashMap instead of flowing directly

Describe the solution you'd like

I suggest adding an extra field to InboundMessage (or similar mechanism) to allow callers to pass custom context that flows through the chain:

InboundMessage.extra → MsgContext.extra → Gateway → RuntimeContext

Option A: Add extra to InboundMessage

public record InboundMessage(
        String channelId,
        String accountId,
        Peer peer,
        String senderId,
        Peer parentPeer,
        String guild,
        String team,
        Set<String> roles,
        List<Msg> messages,
        String preferredAgentId,
        Map<String, String> extra  // ← New field
) {
    // ...
}

Then ChannelRouter.buildContext would merge it:

private MsgContext buildContext(InboundMessage msg, DmScope dmScope, String agentId, String userId) {
    Map<String, String> extra = new HashMap<>();
    extra.put("agentId", agentId);
    if (msg.extra() != null) {
        extra.putAll(msg.extra());  // ← Merge InboundMessage.extra
    }
    // ... rest of logic
}

Option B: Add extra to MsgContext builder in ChannelRouter

Allow ChannelRouter to accept a context enrichment callback:

public interface ChannelRouter {
    RouteResult resolveRoute(InboundMessage msg, BiConsumer<String, String> extraEnricher);
}

Describe alternatives you've considered

  1. ThreadLocal / RequestAttributes - Couples Gateway to Servlet API, not suitable for non-web scenarios
  2. Storing in Msg.accountId - Overloading existing fields is hacky
  3. Custom middleware to inject context - Requires knowing the context before dispatch, which defeats the purpose

The ConcurrentHashMap workaround works but is error-prone and feels like fighting the framework rather than working with it.

Additional context

Current architecture:

Controller (extracts modelConfigId, datasourceId)
    ↓
Service.put(userId, config)  ← ConcurrentHashMap
    ↓
Channel.dispatchStream(inbound)
    ↓
Gateway.runStream(msgContext)
    ↓
Gateway.get(userId)  ← ConcurrentHashMap
    ↓
RuntimeContext.put("modelConfigId", ...)
    ↓
Middleware / Tool reads ctx.get("modelConfigId")

Desired architecture:

Controller (extracts modelConfigId, datasourceId)
    ↓
Service.buildInbound(extra={modelConfigId, datasourceId})
    ↓
Channel.dispatchStream(inbound)
    ↓
Gateway.runStream(msgContext)  ← MsgContext.extra contains modelConfigId
    ↓
RuntimeContext.put("modelConfigId", ctx.extra().get("modelConfigId"))
    ↓
Middleware / Tool reads ctx.get("modelConfigId")

This would eliminate the need for ModelContext and DatasourceContext helper classes entirely.

Activity

  1. added
    enhancement
    on Jun 30, 2026
  2. added
    area/core/agent
    on Jul 11, 2026
  3. xzxiaoshan commented on Nov 3, 2026

    @xzxiaoshan
    Collaborator

    This has been implemented (and went further than proposed) by #2604:

    • InboundMessage.runtimeContext() + withRuntimeContext(...) — carry a caller-built RuntimeContext through Channel.dispatchStream into the Gateway turn
    • ChatUiChannel SendOptions.withRuntimeContext(...) / .putAttribute(key, value) — the Controller-layer entry for per-request business params (tenantId, modelConfigId, …)
    • ChannelRuntimeContextResolver — pluggable hook on HarnessGateway for channel adapters

    Note the design differs from the proposal: instead of adding extra to InboundMessage and copying it into MsgContext.extra, the full RuntimeContext rides on InboundMessage directly — MsgContext.extra participates in canonicalKey() (session routing), so business params there would fragment sessions. Gateway identity fields (sessionId, userId, …) still win on conflict. See docs: docs/v2/en/docs/harness/channel.md.

    Closing as completed — feel free to reopen if anything's missing.

  4. moved this from In progress to Done in AgentScope Javaon Nov 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/core/agentenhancement

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions