Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .github/workflows/mcp-e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,19 @@ jobs:
working-directory: plugins/btrace-observability/mcp
run: ./gradlew --no-daemon e2eTest

# The e2e tests use BTRACE_JAR, so they cannot see a dependency users fail to resolve. This starts
# the server the way the plugin manifests do, with nothing cached.
- name: Start the MCP server from a clean JBang install
run: |
curl -Ls https://sh.jbang.dev | bash -s - version
export JBANG_DIR="$(mktemp -d)" JBANG_REPO="$(mktemp -d)"
printf '%s\n' \
'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"ci","version":"1"}}}' \
'{"jsonrpc":"2.0","method":"notifications/initialized"}' \
'{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' |
timeout 300 "$HOME/.jbang/bin/jbang" plugins/btrace-observability/mcp/src/main/java/io/btrace/mcp/BTraceMcpServer.java |
grep '"id":2' | grep -q deploy_oneliner

- name: Upload e2e logs and reports
if: failure()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ one another so the workflow instructions and supporting scripts are maintained o
.claude-plugin/marketplace.json Claude Code catalog
.agents/plugins/marketplace.json Codex catalog
package.json Pi package manifest
extensions/mcp-servers.ts Pi MCP server registration
plugins/<name>/skills/ shared Agent Skills content
plugins/<name>/.claude-plugin/ Claude Code manifest
plugins/<name>/.codex-plugin/ Codex manifest
Expand All @@ -41,6 +42,9 @@ plugins/<name>/.codex-plugin/ Codex manifest
pi install git:github.com/btraceio/agent-plugins
```

The package registers the `jafar` and `btrace` MCP servers through an extension. They start with JBang, and
`btrace` also needs JDK 11 or later on the host that can attach to the target JVM.

### Codex

Clone this repository and add the checkout as a team marketplace:
Expand Down
22 changes: 22 additions & 0 deletions extensions/mcp-servers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Pi loads MCP servers only from mcp.json or an extension, never from a package manifest, so this
// registers the servers the shared skills call. A server of the same name in mcp.json takes precedence.
import { fileURLToPath } from "node:url";

const BTRACE_SERVER = fileURLToPath(
new URL("../plugins/btrace-observability/mcp/src/main/java/io/btrace/mcp/BTraceMcpServer.java", import.meta.url),
);

export default function (pi: {
registerMcpServer(name: string, config: { command: string; args: string[]; description: string }): void;
}) {
pi.registerMcpServer("jafar", {
command: "jbang",
args: ["jfr-mcp@btraceio", "--stdio", "--attach"],
description: "Analyse JFR, pprof, OTLP and HPROF profiling data",
});
pi.registerMcpServer("btrace", {
command: "jbang",
args: [BTRACE_SERVER],
description: "Attach BTrace probes to a running JVM",
});
}
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@
"agent-skills"
],
"pi": {
"extensions": [
"./extensions/mcp-servers.ts"
],
"skills": [
"./plugins/btrace-development/skills",
"./plugins/btrace-observability/skills",
"./plugins/jfr-analyzer/skills",
"./plugins/jafar-perf/skills",
"./plugins/perf-engineer/skills"
],
"mcp": "./plugins/jafar-perf/.mcp.json"
]
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,31 @@ void targetSurvivesTheWholeSession() {
assertTrue(server.isAlive(), "MCP server died during the session");
}

@Test
@Order(13)
void aBusyPortIsReportedWithTheArgumentThatAvoidsIt() throws Exception {
// The client checks the port only for a JVM with no agent yet, so this needs a fresh target.
Process freshApp =
new ProcessBuilder(javaTool("java"), "-cp", requiredProperty("e2e.sampleClasspath"), TARGET)
.redirectError(new File(System.getProperty("e2e.logDir", "build/e2e"), "fresh-app.err"))
.start();
try (ServerSocket busy = new ServerSocket(0)) {
awaitReady(freshApp);
Map<String, Object> arguments =
args("oneliner", TARGET + "::process @return { print method }");
arguments.put("pid", String.valueOf(freshApp.pid()));
arguments.put("port", busy.getLocalPort());

Map<String, Object> result = server.callTool("deploy_oneliner", arguments, CALL);

assertTrue(isError(result), text(result));
assertTrue(text(result).contains("Port " + busy.getLocalPort() + " unavailable"), text(result));
assertTrue(text(result).contains("'port' argument"), text(result));
} finally {
freshApp.destroyForcibly();
}
}

private Map<String, Object> tool(String name, Object... keyValues) throws Exception {
Map<String, Object> arguments = args(keyValues);
arguments.put("pid", pid);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,17 @@
package io.btrace.mcp;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -37,6 +40,7 @@
public final class BTraceClient {
private static final Logger log = LoggerFactory.getLogger(BTraceClient.class);
private static final String JAR_PATH_PROPERTY = "btrace.jar.path";
private static final Pattern PORT_UNAVAILABLE = Pattern.compile("Port \\d+ unavailable.*");

@FunctionalInterface
public interface CommandListener {
Expand Down Expand Up @@ -74,7 +78,12 @@ public static BTraceClient create(int port) throws Exception {
ClassLoader loader =
(ClassLoader) constructor.newInstance(jar, "client", BTraceClient.class.getClassLoader());
Class<?> clientClass = loader.loadClass("io.btrace.client.Client");
Object client = clientClass.getConstructor(int.class).newInstance(port);
Object client;
try {
client = clientClass.getConstructor(int.class).newInstance(port);
} catch (InvocationTargetException e) {
throw unwrap(e);
}
return new BTraceClient(
client,
clientClass,
Expand All @@ -86,43 +95,56 @@ public static BTraceClient create(int port) throws Exception {
public byte[] compileSource(String fileName, String source, String classPath, PrintWriter errors)
throws Exception {
return (byte[])
clientClass
.getMethod("compileSource", String.class, String.class, String.class, PrintWriter.class)
.invoke(delegate, fileName, source, classPath, errors);
call(
clientClass.getMethod(
"compileSource", String.class, String.class, String.class, PrintWriter.class),
delegate,
fileName,
source,
classPath,
errors);
}

public String onelinerSource(String expression, String className) throws Exception {
ClassLoader loader = clientClass.getClassLoader();
Class<?> parser = loader.loadClass("io.btrace.compiler.oneliner.OnelinerParser");
Object ast = parser.getMethod("parse", String.class).invoke(null, expression);
Object ast = call(parser.getMethod("parse", String.class), null, expression);
Class<?> validator = loader.loadClass("io.btrace.compiler.oneliner.OnelinerValidator");
for (Method method : validator.getMethods()) {
if (method.getName().equals("validate") && method.getParameterCount() == 2) {
method.invoke(null, ast, expression);
call(method, null, ast, expression);
break;
}
}
Class<?> generator = loader.loadClass("io.btrace.compiler.oneliner.OnelinerCodeGenerator");
for (Method method : generator.getMethods()) {
if (method.getName().equals("generate") && method.getParameterCount() == 2) {
return (String) method.invoke(null, ast, className);
return (String) call(method, null, ast, className);
}
}
throw new IllegalStateException("BTrace oneliner generator is unavailable");
}

public void attach(String pid, String systemClassPath, String bootstrapClassPath) throws Exception {
clientClass
.getMethod("attach", String.class, String.class, String.class)
.invoke(delegate, pid, systemClassPath, bootstrapClassPath);
call(
clientClass.getMethod("attach", String.class, String.class, String.class),
delegate,
pid,
systemClassPath,
bootstrapClassPath);
}

public void submit(String host, String fileName, byte[] code, String[] args, CommandListener listener)
throws Exception {
clientClass
.getMethod(
"submit", String.class, String.class, byte[].class, String[].class, commandListenerClass)
.invoke(delegate, host, fileName, code, args, listenerProxy(listener));
call(
clientClass.getMethod(
"submit", String.class, String.class, byte[].class, String[].class, commandListenerClass),
delegate,
host,
fileName,
code,
args,
listenerProxy(listener));
}

/**
Expand All @@ -147,36 +169,40 @@ public Thread submitInBackground(
}

public void listProbes(String host, CommandListener listener) throws Exception {
clientClass
.getMethod("connectAndListProbes", String.class, commandListenerClass)
.invoke(delegate, host, listenerProxy(listener));
call(
clientClass.getMethod("connectAndListProbes", String.class, commandListenerClass),
delegate,
host,
listenerProxy(listener));
}

/** Reconnects to a detached probe and stops it; returns once the agent confirms the exit. */
public void exitProbe(String host, String probeId) throws Exception {
clientClass
.getMethod("connectAndExitProbe", String.class, String.class)
.invoke(delegate, host, probeId);
call(
clientClass.getMethod("connectAndExitProbe", String.class, String.class),
delegate,
host,
probeId);
}

public void sendExit(int code) throws Exception {
clientClass.getMethod("sendExit", int.class).invoke(delegate, code);
call(clientClass.getMethod("sendExit", int.class), delegate, code);
}

public void sendDisconnect() throws Exception {
clientClass.getMethod("sendDisconnect").invoke(delegate);
call(clientClass.getMethod("sendDisconnect"), delegate);
}

public void sendEvent() throws Exception {
clientClass.getMethod("sendEvent").invoke(delegate);
call(clientClass.getMethod("sendEvent"), delegate);
}

public void sendEvent(String name) throws Exception {
clientClass.getMethod("sendEvent", String.class).invoke(delegate, name);
call(clientClass.getMethod("sendEvent", String.class), delegate, name);
}

public void close() throws Exception {
clientClass.getMethod("close").invoke(delegate);
call(clientClass.getMethod("close"), delegate);
}

public int commandType(Object command) throws Exception {
Expand All @@ -196,6 +222,34 @@ public String printableText(Object command) throws Exception {
return output.toString();
}

private static Object call(Method method, Object target, Object... args) throws Exception {
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
throw unwrap(e);
}
}

/**
* Returns the exception the client actually threw. Reflection wraps it in an exception whose
* message is null, and the tools report that message to the user.
*/
private static Exception unwrap(InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException
&& cause.getMessage() != null
&& PORT_UNAVAILABLE.matcher(cause.getMessage()).matches()) {
return new IOException(
cause.getMessage()
+ " Another BTrace agent or process is using it; pass a different 'port' argument.",
cause);
}
if (cause instanceof Exception && cause.getMessage() != null) {
return (Exception) cause;
}
return new IllegalStateException(String.valueOf(cause), cause);
}

private Object listenerProxy(CommandListener listener) {
InvocationHandler handler =
(proxy, method, args) -> {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//REPOS mavencentral,central-snapshots=https://central.sonatype.com/repository/maven-snapshots/
//DEPS io.btrace:btrace:3.0.0-SNAPSHOT
//DEPS org.slf4j:slf4j-api:2.0.18
//DEPS org.slf4j:slf4j-simple:2.0.18
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,14 @@ public byte[] compileSource(String fileName, String source, String classPath, Pr
return (fileName + ':' + source + ':' + classPath).getBytes();
}

public void attach(String pid, String systemClassPath, String bootstrapClassPath) {
public void attach(String pid, String systemClassPath, String bootstrapClassPath)
throws java.io.IOException {
if (pid.equals("port-busy")) {
throw new java.io.IOException("Port " + port + " unavailable.");
}
if (pid.equals("no-message")) {
throw new java.io.IOException();
}
attachedPid = pid;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import io.btrace.client.Client;
import io.btrace.core.comm.Command;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.concurrent.CountDownLatch;
Expand Down Expand Up @@ -70,6 +72,25 @@ void invokesTheMaskedClientContractReflectively() throws Exception {
assertTrue(delegate.closed);
}

@Test
void aBusyPortNamesThePortAndTheArgumentThatAvoidsIt() throws Exception {
BTraceClient client = BTraceClient.create(2020);

IOException e = assertThrows(IOException.class, () -> client.attach("port-busy", null, "."));

assertTrue(e.getMessage().startsWith("Port 2020 unavailable. Another"), e.getMessage());
assertTrue(e.getMessage().contains("'port' argument"), e.getMessage());
}

@Test
void aFailureWithoutAMessageStillDescribesItself() throws Exception {
BTraceClient client = BTraceClient.create(2020);

Exception e = assertThrows(Exception.class, () -> client.attach("no-message", null, "."));

assertEquals("java.io.IOException", e.getMessage());
}

@Test
void clientManagerTracksAndCleansUpClients() throws Exception {
BTraceClient client = BTraceClient.create(2021);
Expand Down
4 changes: 3 additions & 1 deletion plugins/jafar-perf/agents/concurrency-analyst.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
---
name: concurrency-analyst
description: Specialist for thread and contention analysis of a JFR recording — thread states, monitor contention, parking, executor queue saturation, and per-endpoint latency attribution. Dispatch when triage shows threads blocked or waiting rather than running, or when the complaint is p99 latency rather than throughput.
tools: mcp__jafar__jfr_tsa, mcp__jafar__jfr_use, mcp__jafar__jfr_query, mcp__jafar__jfr_list_types, mcp__jafar__jfr_stackprofile, mcp__jafar__pprof_tsa, Read, Grep, Glob
tools: mcp__plugin_jafar-perf_jafar__jfr_open, mcp__plugin_jafar-perf_jafar__jfr_close, mcp__plugin_jafar-perf_jafar__jfr_tsa, mcp__plugin_jafar-perf_jafar__jfr_use, mcp__plugin_jafar-perf_jafar__jfr_query, mcp__plugin_jafar-perf_jafar__jfr_list_types, mcp__plugin_jafar-perf_jafar__jfr_stackprofile, mcp__plugin_jafar-perf_jafar__pprof_tsa, Read, Grep, Glob
skills: latency, report
model: sonnet
---

You analyse what threads are waiting for. Follow the `latency` skill; report in the
`report` format.

If you were not given an open session id, open the artifact yourself and close it when you finish.

Run `jfr_tsa` with `correlateBlocking=true` first and read `stateDistribution` before
anything else — if the recording is RUNNABLE-dominated this is a CPU question and you
should say so rather than manufacturing a contention story.
Expand Down
Loading
Loading