diff --git a/CHANGELOG.next-release.md b/CHANGELOG.next-release.md
index 91ab0d62d03..49367f5033a 100644
--- a/CHANGELOG.next-release.md
+++ b/CHANGELOG.next-release.md
@@ -13,6 +13,7 @@ This file contains all changes which are not released yet.
# Features and enhancements
+- Add experimental auto-instrumentation for Spring AI 2.x chat models, embedding models, vector stores, client tool callbacks, and MCP server tool calls, with opt-in AI content capture - [#4622](https://github.com/elastic/apm-agent-java/pull/4622)
# Deprecations
diff --git a/apm-agent-builds/pom.xml b/apm-agent-builds/pom.xml
index 32829cdf069..35f12bb67fa 100644
--- a/apm-agent-builds/pom.xml
+++ b/apm-agent-builds/pom.xml
@@ -346,6 +346,11 @@
apm-sparkjava-plugin
${project.version}
+
+ ${project.groupId}
+ apm-spring-ai-plugin
+ ${project.version}
+
${project.groupId}
apm-spring-resttemplate-plugin
diff --git a/apm-agent-common/src/test/java/co/elastic/apm/agent/test/AgentTestContainer.java b/apm-agent-common/src/test/java/co/elastic/apm/agent/test/AgentTestContainer.java
index e73a391afe1..251333b2468 100644
--- a/apm-agent-common/src/test/java/co/elastic/apm/agent/test/AgentTestContainer.java
+++ b/apm-agent-common/src/test/java/co/elastic/apm/agent/test/AgentTestContainer.java
@@ -212,7 +212,7 @@ public AppServer withHttpPort(int port) {
}
public String getBaseUrl() {
- return String.format("http://%s:%d", getContainerIpAddress(), getMappedPort(webPort));
+ return String.format("http://%s:%d", getHost(), getMappedPort(webPort));
}
public int getHttpPort() {
diff --git a/apm-agent-core/src/main/java/co/elastic/apm/agent/configuration/CoreConfigurationImpl.java b/apm-agent-core/src/main/java/co/elastic/apm/agent/configuration/CoreConfigurationImpl.java
index d73e4185dd9..00e07a73d1e 100644
--- a/apm-agent-core/src/main/java/co/elastic/apm/agent/configuration/CoreConfigurationImpl.java
+++ b/apm-agent-core/src/main/java/co/elastic/apm/agent/configuration/CoreConfigurationImpl.java
@@ -261,6 +261,7 @@ public class CoreConfigurationImpl extends ConfigurationOptionProvider implement
"- `transaction.context.request.body`, `error.context.request.body`\n" +
"- `transaction.context.message.body`, `error.context.message.body`\n" +
"- `span.context.db.statement`\n" +
+ "- captured AI content values\n" +
"\nNote that tracing data is limited at the upstream APM server to \n" +
"{apm-guide-ref}/configuration-process.html#max_event_size[`max_event_size`], \n" +
"which defaults to 300kB. If you configure `long_field_max_length` too large, it \n" +
diff --git a/apm-agent-plugins/apm-spring-ai-plugin/pom.xml b/apm-agent-plugins/apm-spring-ai-plugin/pom.xml
new file mode 100644
index 00000000000..b714f9022b3
--- /dev/null
+++ b/apm-agent-plugins/apm-spring-ai-plugin/pom.xml
@@ -0,0 +1,95 @@
+
+
+ 4.0.0
+
+
+ co.elastic.apm
+ apm-agent-plugins
+ 1.57.3-SNAPSHOT
+
+
+ apm-spring-ai-plugin
+ ${project.groupId}:${project.artifactId}
+
+
+ ${project.basedir}/../..
+ true
+ 8
+ 8
+ 2.0.2
+ 3.8.8
+ 2.24.3
+
+
+
+
+ ${project.groupId}
+ apm-agent-core
+ ${project.version}
+
+
+ ${project.groupId}
+ apm-opentelemetry-embedded-metrics-sdk
+ ${project.version}
+
+
+ org.springframework.ai
+ spring-ai-model
+ ${version.spring-ai}
+ provided
+
+
+ org.springframework.ai
+ spring-ai-vector-store
+ ${version.spring-ai}
+ provided
+
+
+ org.springframework.ai
+ spring-ai-mcp-annotations
+ ${version.spring-ai}
+ provided
+
+
+ io.projectreactor
+ reactor-core
+ ${version.reactor}
+ provided
+
+
+ ${project.groupId}
+ apm-opentelemetry-metricsdk-plugin
+ ${project.version}
+ test
+
+
+ org.apache.ivy
+ ivy
+ test
+
+
+
+ org.apache.logging.log4j
+ log4j-api
+ ${version.log4j2-test}
+ test
+
+
+ org.apache.logging.log4j
+ log4j-core
+ ${version.log4j2-test}
+ test
+
+
+
+ com.fasterxml.jackson.core
+ jackson-annotations
+ 2.21
+ test
+
+
+
+
diff --git a/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/AbstractSpringAiInstrumentation.java b/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/AbstractSpringAiInstrumentation.java
new file mode 100644
index 00000000000..2d06a2adb78
--- /dev/null
+++ b/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/AbstractSpringAiInstrumentation.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to Elasticsearch B.V. under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch B.V. licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package co.elastic.apm.agent.springai;
+
+import co.elastic.apm.agent.sdk.ElasticApmInstrumentation;
+import net.bytebuddy.matcher.ElementMatcher;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import static co.elastic.apm.agent.sdk.bytebuddy.CustomElementMatchers.classLoaderCanLoadClass;
+
+abstract class AbstractSpringAiInstrumentation extends ElasticApmInstrumentation {
+
+ @Override
+ public ElementMatcher.Junction getClassLoaderMatcher() {
+ return classLoaderCanLoadClass("org.springframework.ai.model.Model")
+ .and(classLoaderCanLoadClass("org.springframework.ai.observation.conventions.AiOperationType"))
+ // DefaultEmbeddingOptions.Builder was introduced in Spring AI 2.0.
+ .and(classLoaderCanLoadClass("org.springframework.ai.embedding.DefaultEmbeddingOptions$Builder"));
+ }
+
+ @Override
+ public Collection getInstrumentationGroupNames() {
+ return Arrays.asList("spring-ai", "experimental");
+ }
+}
diff --git a/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/ChatModelInstrumentation.java b/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/ChatModelInstrumentation.java
new file mode 100644
index 00000000000..1bef082a15e
--- /dev/null
+++ b/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/ChatModelInstrumentation.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to Elasticsearch B.V. under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch B.V. licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package co.elastic.apm.agent.springai;
+
+import co.elastic.apm.agent.tracer.Span;
+import net.bytebuddy.asm.Advice;
+import net.bytebuddy.description.NamedElement;
+import net.bytebuddy.description.method.MethodDescription;
+import net.bytebuddy.description.type.TypeDescription;
+import net.bytebuddy.matcher.ElementMatcher;
+import org.springframework.ai.chat.model.ChatResponse;
+import org.springframework.ai.chat.prompt.Prompt;
+
+import javax.annotation.Nullable;
+
+import static net.bytebuddy.matcher.ElementMatchers.hasSuperType;
+import static net.bytebuddy.matcher.ElementMatchers.isInterface;
+import static net.bytebuddy.matcher.ElementMatchers.nameContains;
+import static net.bytebuddy.matcher.ElementMatchers.named;
+import static net.bytebuddy.matcher.ElementMatchers.not;
+import static net.bytebuddy.matcher.ElementMatchers.takesArgument;
+import static net.bytebuddy.matcher.ElementMatchers.takesArguments;
+
+public class ChatModelInstrumentation extends AbstractSpringAiInstrumentation {
+
+ @Override
+ public ElementMatcher super NamedElement> getTypeMatcherPreFilter() {
+ return nameContains("ChatModel");
+ }
+
+ @Override
+ public ElementMatcher super TypeDescription> getTypeMatcher() {
+ return not(isInterface()).and(hasSuperType(named("org.springframework.ai.chat.model.ChatModel")));
+ }
+
+ @Override
+ public ElementMatcher super MethodDescription> getMethodMatcher() {
+ return named("call").and(takesArguments(1))
+ .and(takesArgument(0, named("org.springframework.ai.chat.prompt.Prompt")));
+ }
+
+ @Override
+ public String getAdviceClassName() {
+ return getClass().getName() + "$ChatModelAdvice";
+ }
+
+ public static class ChatModelAdvice {
+
+ @Nullable
+ @Advice.OnMethodEnter(suppress = Throwable.class, inline = false)
+ public static Object onEnter(@Advice.Argument(0) Prompt prompt) {
+ Span> span = SpringAiSpanHelper.startModelSpan("chat", prompt, false);
+ return span == null ? null : span.activate();
+ }
+
+ @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class, inline = false)
+ public static void onExit(@Advice.Enter @Nullable Object spanObject,
+ @Advice.Return @Nullable ChatResponse response,
+ @Advice.Thrown @Nullable Throwable thrown) {
+ SpringAiSpanHelper.endChatSpan((Span>) spanObject, response, thrown);
+ }
+ }
+}
diff --git a/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/EmbeddingModelInstrumentation.java b/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/EmbeddingModelInstrumentation.java
new file mode 100644
index 00000000000..08c540a3aca
--- /dev/null
+++ b/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/EmbeddingModelInstrumentation.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to Elasticsearch B.V. under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch B.V. licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package co.elastic.apm.agent.springai;
+
+import co.elastic.apm.agent.tracer.Span;
+import net.bytebuddy.asm.Advice;
+import net.bytebuddy.description.NamedElement;
+import net.bytebuddy.description.method.MethodDescription;
+import net.bytebuddy.description.type.TypeDescription;
+import net.bytebuddy.matcher.ElementMatcher;
+import org.springframework.ai.embedding.EmbeddingRequest;
+import org.springframework.ai.embedding.EmbeddingResponse;
+
+import javax.annotation.Nullable;
+
+import static net.bytebuddy.matcher.ElementMatchers.hasSuperType;
+import static net.bytebuddy.matcher.ElementMatchers.isInterface;
+import static net.bytebuddy.matcher.ElementMatchers.nameContains;
+import static net.bytebuddy.matcher.ElementMatchers.named;
+import static net.bytebuddy.matcher.ElementMatchers.not;
+import static net.bytebuddy.matcher.ElementMatchers.takesArgument;
+import static net.bytebuddy.matcher.ElementMatchers.takesArguments;
+
+public class EmbeddingModelInstrumentation extends AbstractSpringAiInstrumentation {
+
+ @Override
+ public ElementMatcher super NamedElement> getTypeMatcherPreFilter() {
+ return nameContains("Embedding");
+ }
+
+ @Override
+ public ElementMatcher super TypeDescription> getTypeMatcher() {
+ return not(isInterface()).and(hasSuperType(named("org.springframework.ai.embedding.EmbeddingModel")));
+ }
+
+ @Override
+ public ElementMatcher super MethodDescription> getMethodMatcher() {
+ return named("call").and(takesArguments(1))
+ .and(takesArgument(0, named("org.springframework.ai.embedding.EmbeddingRequest")));
+ }
+
+ @Override
+ public String getAdviceClassName() {
+ return getClass().getName() + "$EmbeddingModelAdvice";
+ }
+
+ public static class EmbeddingModelAdvice {
+
+ @Nullable
+ @Advice.OnMethodEnter(suppress = Throwable.class, inline = false)
+ public static Object onEnter(@Advice.Argument(0) EmbeddingRequest request) {
+ Span> span = SpringAiSpanHelper.startEmbeddingSpan(request);
+ return span == null ? null : span.activate();
+ }
+
+ @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class, inline = false)
+ public static void onExit(@Advice.Enter @Nullable Object spanObject,
+ @Advice.Return @Nullable EmbeddingResponse response,
+ @Advice.Thrown @Nullable Throwable thrown) {
+ SpringAiSpanHelper.endEmbeddingSpan((Span>) spanObject, response, thrown);
+ }
+ }
+}
diff --git a/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/McpAsyncToolCallbackInstrumentation.java b/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/McpAsyncToolCallbackInstrumentation.java
new file mode 100644
index 00000000000..222d44df632
--- /dev/null
+++ b/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/McpAsyncToolCallbackInstrumentation.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to Elasticsearch B.V. under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch B.V. licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package co.elastic.apm.agent.springai;
+
+import co.elastic.apm.agent.sdk.internal.util.PrivilegedActionUtils;
+import io.modelcontextprotocol.spec.McpSchema;
+import net.bytebuddy.asm.Advice;
+import net.bytebuddy.description.NamedElement;
+import net.bytebuddy.description.method.MethodDescription;
+import net.bytebuddy.description.type.TypeDescription;
+import net.bytebuddy.matcher.ElementMatcher;
+import reactor.core.publisher.Mono;
+
+import javax.annotation.Nullable;
+
+import static net.bytebuddy.matcher.ElementMatchers.nameEndsWith;
+import static net.bytebuddy.matcher.ElementMatchers.named;
+import static net.bytebuddy.matcher.ElementMatchers.namedOneOf;
+import static net.bytebuddy.matcher.ElementMatchers.returns;
+import static net.bytebuddy.matcher.ElementMatchers.takesArgument;
+import static net.bytebuddy.matcher.ElementMatchers.takesArguments;
+
+public class McpAsyncToolCallbackInstrumentation extends AbstractSpringAiInstrumentation {
+
+ private static final String CALL_TOOL_REQUEST =
+ "io.modelcontextprotocol.spec.McpSchema$CallToolRequest";
+
+ @Override
+ public ElementMatcher super NamedElement> getTypeMatcherPreFilter() {
+ return nameEndsWith("McpToolMethodCallback");
+ }
+
+ @Override
+ public ElementMatcher super TypeDescription> getTypeMatcher() {
+ return namedOneOf(
+ "org.springframework.ai.mcp.annotation.method.tool.AsyncMcpToolMethodCallback",
+ "org.springframework.ai.mcp.annotation.method.tool.AsyncStatelessMcpToolMethodCallback");
+ }
+
+ @Override
+ public ElementMatcher super MethodDescription> getMethodMatcher() {
+ return named("apply")
+ .and(takesArguments(2))
+ .and(takesArgument(1, named(CALL_TOOL_REQUEST)))
+ .and(returns(named("reactor.core.publisher.Mono")));
+ }
+
+ @Override
+ public String getAdviceClassName() {
+ return getClass().getName() + "$McpAsyncToolCallbackAdvice";
+ }
+
+ public static class McpAsyncToolCallbackAdvice {
+
+ @Nullable
+ @Advice.AssignReturned.ToReturned
+ @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class, inline = false)
+ public static Mono> onExit(@Advice.Argument(1) McpSchema.CallToolRequest request,
+ @Advice.Origin Class> callbackClass,
+ @Advice.Return @Nullable Mono> result,
+ @Advice.Thrown @Nullable Throwable thrown) {
+ if (thrown != null || result == null) {
+ return result;
+ }
+ return SpringAiMcpServerHelper.wrapAsyncResult(
+ request, result, PrivilegedActionUtils.getClassLoader(callbackClass));
+ }
+ }
+}
diff --git a/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/McpSyncToolCallbackInstrumentation.java b/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/McpSyncToolCallbackInstrumentation.java
new file mode 100644
index 00000000000..75121b0bdc2
--- /dev/null
+++ b/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/McpSyncToolCallbackInstrumentation.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to Elasticsearch B.V. under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch B.V. licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package co.elastic.apm.agent.springai;
+
+import co.elastic.apm.agent.sdk.internal.util.PrivilegedActionUtils;
+import co.elastic.apm.agent.tracer.Transaction;
+import io.modelcontextprotocol.spec.McpSchema;
+import net.bytebuddy.asm.Advice;
+import net.bytebuddy.description.NamedElement;
+import net.bytebuddy.description.method.MethodDescription;
+import net.bytebuddy.description.type.TypeDescription;
+import net.bytebuddy.matcher.ElementMatcher;
+
+import javax.annotation.Nullable;
+
+import static net.bytebuddy.matcher.ElementMatchers.nameEndsWith;
+import static net.bytebuddy.matcher.ElementMatchers.named;
+import static net.bytebuddy.matcher.ElementMatchers.namedOneOf;
+import static net.bytebuddy.matcher.ElementMatchers.returns;
+import static net.bytebuddy.matcher.ElementMatchers.takesArgument;
+import static net.bytebuddy.matcher.ElementMatchers.takesArguments;
+
+public class McpSyncToolCallbackInstrumentation extends AbstractSpringAiInstrumentation {
+
+ private static final String CALL_TOOL_REQUEST =
+ "io.modelcontextprotocol.spec.McpSchema$CallToolRequest";
+ private static final String CALL_TOOL_RESULT =
+ "io.modelcontextprotocol.spec.McpSchema$CallToolResult";
+
+ @Override
+ public ElementMatcher super NamedElement> getTypeMatcherPreFilter() {
+ return nameEndsWith("McpToolMethodCallback");
+ }
+
+ @Override
+ public ElementMatcher super TypeDescription> getTypeMatcher() {
+ return namedOneOf(
+ "org.springframework.ai.mcp.annotation.method.tool.SyncMcpToolMethodCallback",
+ "org.springframework.ai.mcp.annotation.method.tool.SyncStatelessMcpToolMethodCallback");
+ }
+
+ @Override
+ public ElementMatcher super MethodDescription> getMethodMatcher() {
+ return named("apply")
+ .and(takesArguments(2))
+ .and(takesArgument(1, named(CALL_TOOL_REQUEST)))
+ .and(returns(named(CALL_TOOL_RESULT)));
+ }
+
+ @Override
+ public String getAdviceClassName() {
+ return getClass().getName() + "$McpSyncToolCallbackAdvice";
+ }
+
+ public static class McpSyncToolCallbackAdvice {
+
+ @Nullable
+ @Advice.OnMethodEnter(suppress = Throwable.class, inline = false)
+ public static Object onEnter(@Advice.Argument(1) McpSchema.CallToolRequest request,
+ @Advice.Origin Class> callbackClass) {
+ Transaction> transaction = SpringAiMcpServerHelper.startTransaction(
+ request, PrivilegedActionUtils.getClassLoader(callbackClass));
+ return transaction == null ? null : transaction.activate();
+ }
+
+ @Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class, inline = false)
+ public static void onExit(@Advice.Enter @Nullable Object transactionObject,
+ @Advice.Return @Nullable McpSchema.CallToolResult result,
+ @Advice.Thrown @Nullable Throwable thrown) {
+ if (transactionObject == null) {
+ return;
+ }
+ SpringAiMcpServerHelper.endTransaction((Transaction>) transactionObject, result, thrown);
+ }
+ }
+}
diff --git a/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/SpringAiConfiguration.java b/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/SpringAiConfiguration.java
new file mode 100644
index 00000000000..64c43e353af
--- /dev/null
+++ b/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/SpringAiConfiguration.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to Elasticsearch B.V. under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch B.V. licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package co.elastic.apm.agent.springai;
+
+import org.stagemonitor.configuration.ConfigurationOption;
+import org.stagemonitor.configuration.ConfigurationOptionProvider;
+
+public class SpringAiConfiguration extends ConfigurationOptionProvider {
+
+ private final ConfigurationOption captureSpringAiContent = ConfigurationOption.booleanOption()
+ .key("capture_spring_ai_content")
+ .configurationCategory("AI")
+ .tags("security", "performance", "experimental", "added[1.58.0]")
+ .description("Enables capture of Spring AI prompt and response messages, embedding inputs, vector store documents and queries, and tool arguments and results.\n\n" +
+ "Captured content can contain sensitive information and can significantly increase storage usage. Content capture is disabled by default. " +
+ "Individual captured content values are truncated according to `long_field_max_length`.")
+ .dynamic(true)
+ .buildWithDefault(false);
+
+ public boolean isCaptureSpringAiContent() {
+ return captureSpringAiContent.get();
+ }
+}
diff --git a/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/SpringAiMcpServerHelper.java b/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/SpringAiMcpServerHelper.java
new file mode 100644
index 00000000000..e2f790f918c
--- /dev/null
+++ b/apm-agent-plugins/apm-spring-ai-plugin/src/main/java/co/elastic/apm/agent/springai/SpringAiMcpServerHelper.java
@@ -0,0 +1,167 @@
+/*
+ * Licensed to Elasticsearch B.V. under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch B.V. licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package co.elastic.apm.agent.springai;
+
+import co.elastic.apm.agent.tracer.GlobalTracer;
+import co.elastic.apm.agent.tracer.Outcome;
+import co.elastic.apm.agent.tracer.TraceState;
+import co.elastic.apm.agent.tracer.Tracer;
+import co.elastic.apm.agent.tracer.Transaction;
+import co.elastic.apm.agent.tracer.configuration.CoreConfiguration;
+import co.elastic.apm.agent.tracer.dispatch.AbstractHeaderGetter;
+import co.elastic.apm.agent.tracer.dispatch.TextHeaderGetter;
+import io.modelcontextprotocol.spec.McpSchema;
+import org.springframework.ai.util.JsonHelper;
+import reactor.core.publisher.Mono;
+
+import javax.annotation.Nullable;
+import java.util.Collections;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+final class SpringAiMcpServerHelper {
+
+ private static final Tracer tracer = GlobalTracer.get();
+ private static final SpringAiConfiguration config = tracer.getConfig(SpringAiConfiguration.class);
+ private static final CoreConfiguration coreConfig = tracer.getConfig(CoreConfiguration.class);
+ private static final JsonHelper jsonHelper = new JsonHelper();
+
+ private SpringAiMcpServerHelper() {
+ }
+
+ @Nullable
+ static Transaction> startTransaction(McpSchema.CallToolRequest request,
+ @Nullable ClassLoader initiatingClassLoader) {
+ Map metadata = request.meta();
+ Transaction> transaction = tracer.startChildTransaction(
+ metadata == null ? Collections.emptyMap() : metadata,
+ McpMetaHeaderGetter.INSTANCE,
+ initiatingClassLoader);
+ if (transaction == null) {
+ return null;
+ }
+
+ String toolName = request.name();
+ transaction.withName("tools/call " + toolName)
+ .withType(Transaction.TYPE_REQUEST)
+ .withOtelAttribute("mcp.method.name", "tools/call")
+ .withOtelAttribute("gen_ai.operation.name", "execute_tool")
+ .withOtelAttribute("gen_ai.tool.name", toolName);
+ captureContent(transaction, "gen_ai.tool.call.arguments", request.arguments());
+ return transaction;
+ }
+
+ @SuppressWarnings("unchecked")
+ static Mono> wrapAsyncResult(final McpSchema.CallToolRequest request, final Mono> source,
+ @Nullable final ClassLoader initiatingClassLoader) {
+ final Mono typedSource = (Mono) source;
+ return Mono.defer(() -> {
+ final Transaction> transaction = startTransaction(request, initiatingClassLoader);
+ if (transaction == null) {
+ return typedSource;
+ }
+ final AtomicBoolean ended = new AtomicBoolean();
+ transaction.withSync(false);
+ return typedSource
+ .doOnSuccess(result -> {
+ if (ended.compareAndSet(false, true)) {
+ endAsyncTransaction(transaction, result, null);
+ }
+ })
+ .doOnError(failure -> {
+ if (ended.compareAndSet(false, true)) {
+ endAsyncTransaction(transaction, null, failure);
+ }
+ })
+ .doOnCancel(() -> {
+ if (ended.compareAndSet(false, true)) {
+ endAsyncTransaction(transaction, null, null);
+ }
+ })
+ .contextWrite(context -> context.put(TraceState.class, transaction));
+ });
+ }
+
+ static void endTransaction(Transaction> transaction,
+ @Nullable McpSchema.CallToolResult result,
+ @Nullable Throwable thrown) {
+ if (thrown == null) {
+ addResult(transaction, result);
+ }
+ transaction.captureException(thrown)
+ .withOutcome(isFailure(result, thrown) ? Outcome.FAILURE : Outcome.SUCCESS)
+ .deactivate()
+ .end();
+ }
+
+ private static void endAsyncTransaction(Transaction> transaction,
+ @Nullable McpSchema.CallToolResult result,
+ @Nullable Throwable thrown) {
+ if (thrown == null) {
+ addResult(transaction, result);
+ }
+ transaction.captureException(thrown)
+ .withOutcome(isFailure(result, thrown) ? Outcome.FAILURE : Outcome.SUCCESS)
+ .end();
+ }
+
+ private static boolean isFailure(@Nullable McpSchema.CallToolResult result,
+ @Nullable Throwable thrown) {
+ return thrown != null || result != null && Boolean.TRUE.equals(result.isError());
+ }
+
+ private static void addResult(Transaction> transaction,
+ @Nullable McpSchema.CallToolResult result) {
+ if (result == null) {
+ return;
+ }
+ Object content = result.structuredContent() == null ? result.content() : result.structuredContent();
+ captureContent(transaction, "gen_ai.tool.call.result", content);
+ }
+
+ private static void captureContent(Transaction> transaction, String key,
+ @Nullable Object content) {
+ if (!config.isCaptureSpringAiContent() || content == null) {
+ return;
+ }
+ String value = jsonHelper.toJson(content);
+ transaction.withOtelAttribute(key, truncate(value, coreConfig.getLongFieldMaxLength()));
+ }
+
+ private static String truncate(String value, int maxCodePoints) {
+ if (maxCodePoints < 0 || value.codePointCount(0, value.length()) <= maxCodePoints) {
+ return value;
+ }
+ return value.substring(0, value.offsetByCodePoints(0, maxCodePoints));
+ }
+
+ private static class McpMetaHeaderGetter
+ extends AbstractHeaderGetter>
+ implements TextHeaderGetter