Skip to content

How can the MCP Client dynamically set the Header? #2658

Open
@big-mouth-cn

Description

@big-mouth-cn

I have prepared an MCP Server and am about to get the X-Key from the HTTP request header. However, when developing the MCP Client with SpringBoot, I don’t know how to dynamically set the X-Key and update it based on different user identities.

After reviewing the source code, the only feasible approach I could think of was using a Filter to make the changes. However, I realized that the threads for requesting the large model and for invoking the MCP Server are not the same, so sharing the X-Key within the same thread is not possible.

Is there any way to help me solve this problem? thanks.

spring-ai version is: 1.0.0-M6

@Slf4j
@Configuration
public class WebClientBuilderAutoConfiguration {

    @Bean
    public WebClient.Builder webClientBuilder() {
        return WebClient.builder().filter(new ExchangeFilterFunction() {
            @Override
            public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
                log.info("Thread: {}", Thread.currentThread());
                User loginUser = ContextFactory.getLoginUser();
                if (null != loginUser) {
                    String accessKey = loginUser.getAccessKey();
                    ClientRequest newRequest = ClientRequest.from(request)
                            .headers(headers -> {
                                headers.set(Constants.HEADER_ACCESS_KEY, accessKey);
                            })
                            .build();
                    return next.exchange(newRequest);
                } else {
                    return next.exchange(request);
                }
            }
        });
    }
}
2025-04-07T19:55:16.469+08:00  INFO 44353 --- [nio-8070-exec-9] .l.a.a.WebClientBuilderAutoConfiguration : Thread: Thread[http-nio-8070-exec-9,5,main]
2025-04-07T19:55:16.489+08:00  INFO 44353 --- [nio-8070-exec-9] .l.a.a.WebClientBuilderAutoConfiguration : Thread: Thread[http-nio-8070-exec-9,5,main]
2025-04-07T19:56:29.796+08:00  INFO 44353 --- [ent-2-Worker-11] .l.a.a.WebClientBuilderAutoConfiguration : Thread: Thread[HttpClient-2-Worker-11,5,main]
2025-04-07T19:56:32.396+08:00  INFO 44353 --- [ent-2-Worker-11] .l.a.a.WebClientBuilderAutoConfiguration : Thread: Thread[HttpClient-2-Worker-11,5,main]

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions