0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Koog製のAIエージェントからClaude Codeをツールとして使う

0
Last updated at Posted at 2026-08-25

AI生成記事です。

KotlinのAIエージェントフレームワークであるKoogを触っていて、エージェントのツールとしてClaude Code CLIもてるのでは と思ったのでやってみた記録。

AgentがAgentを呼ぶいわゆるA2Aというやつ。それをローカルでやる。Claudeが返した出力をKoogが受けて次の処理を決められる、というのが狙い。

Koogでできること

JetBrains製のKotlin向けAIエージェントフレームワーク。JVMターゲットだけでなくKotlin Multiplatformにも対応している。

エージェントを立てる

最小構成だとこれだけ。

val executor = simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY"))

val agent = AIAgent(
    promptExecutor = executor,
    llmModel = OpenAIModels.Chat.GPT4_1Nano,
    systemPrompt = "You are a helpful assistant.",
    strategy = singleRunStrategy(),
)

val result = agent.run("何かタスク")

promptExecutor がLLMへの接続、llmModel がモデル指定。executorはOpenAI以外にAnthropic / Google / Bedrock / Ollama / OpenRouter / DeepSeek / Mistral が用意されていて、prompt-executor-llms-all を入れると全部入りになる。

agent.run() は suspend fun なので、呼び出し側はコルーチンの中にいる必要がある。CLIなら suspend fun main でいい。

ツールを持たせる

ToolRegistry に登録する。組み込みのファイル操作ツールがあるので、それをそのまま使える。

toolRegistry = ToolRegistry {
    tool(ListDirectoryTool(JVMFileSystemProvider.ReadOnly))
    tool(ReadFileTool(JVMFileSystemProvider.ReadOnly))
    tool(RegexSearchTool(JVMFileSystemProvider.ReadOnly))
}

JVMFileSystemProvider.ReadOnly を渡すと読み取り専用のツールになる。ReadWrite を渡せば EditFileTool も使える。

自前のツールは ToolSet を実装してアノテーションを付ける。

class MyTools : ToolSet {
    @Tool
    @LLMDescription("2つの数を足す")
    fun add(
        @LLMDescription("1つ目の数") a: Int,
        @LLMDescription("2つ目の数") b: Int,
    ): Int = a + b
}

// 登録は tool() ではなく tools()
toolRegistry = ToolRegistry {
    tools(MyTools())
}

リフレクションでメソッドシグネチャからtool定義(JSON Schema)が起こされるので、スキーマを手で書かなくていい。ここが一番ありがたかった。

@LLMDescription はLLM向けのdocコメントという位置づけ。人間は読まないしコンパイラも中身を検証しないが、ツールが選ばれるかどうかはほぼこの文言で決まる。ここは丁寧に書いたほうがいい。

strategyはグラフになっている

singleRunStrategy() は「1タスク投げて1回答をもらう」だけのシンプルなやつ。ただしjarを覗くと戻り値はこうなっている。

public static final AIAgentGraphStrategy<String, String> singleRunStrategy(boolean);

一発回答モードも実体はグラフ戦略で、ノードが1つに縮退しているだけらしい。裏には AIAgentSubgraph を組み合わせるDSLがあって、条件分岐・並列実行・サブグラフごとのツール制限あたりが書ける。

今回使ったのはイベントハンドラだけ。ツール呼び出しをstdoutに出しておくと、エージェントが何をやっているか追える。

AIAgent(...) {
    handleEvents {
        onToolCallStarting { ctx ->
            println("Tool '${ctx.toolName}' called with args: ${ctx.toolArgs}")
        }
    }
}

Claude Codeをツールから呼ぶ

claude -p の非対話モード

Claude Code CLIは -p(--print)を付けると非対話で走って、結果を返して終了する。

claude -p "このプロジェクトが何をするものか要約して" --output-format json

ProcessBuilderで包む

やることは「別プロセスとして起動して、標準出力を読んで、終了を待つ」だけ。

@Tool
@LLMDescription(
    "Runs Claude Code non-interactively against a local repository checkout and returns its " +
        "JSON result. Use this to delegate any investigation, analysis, or code change task " +
        "for the target repo instead of trying to read every file yourself."
)
fun runClaudeCode(
    @LLMDescription("Absolute path to a local checkout of the repository the task applies to")
    repoPath: String,
    @LLMDescription("The task/instruction to give to Claude Code")
    task: String,
): String {
    val workDir = File(repoPath)
    if (!workDir.isDirectory) {
        return "Error: '$repoPath' is not a directory"
    }

    val process = ProcessBuilder(
        claudeBinary,
        "-p", task,
        "--model", model,
        "--output-format", "json",
        "--dangerously-skip-permissions",
    )
        .directory(workDir)
        .redirectErrorStream(true)
        .start()

    val output = process.inputStream.bufferedReader().readText()
    val finished = process.waitFor(timeoutMinutes, TimeUnit.MINUTES)
    if (!finished) {
        process.destroyForcibly()
        return "Error: claude did not finish within $timeoutMinutes minutes"
    }

    return if (process.exitValue() == 0) {
        output
    } else {
        "claude exited with code ${process.exitValue()}:\n$output"
    }
}

サンプルを作ってみた

構成はこれだけ。

src/main/kotlin/
├── Main.kt              # エージェントの組み立てとCLIエントリポイント
└── ClaudeCodeTools.kt   # run_claude_code ツール

build.gradle.kts

plugins {
    kotlin("jvm") version "2.4.10"
    application
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("ai.koog:koog-agents:1.1.1")
    implementation("ai.koog:prompt-executor-llms-all:1.1.1-beta")
    implementation("ai.koog:agents-ext:1.1.1-beta")
}

kotlin {
    jvmToolchain(17)
}

application {
    mainClass.set("MainKt")
}

koog-agents が本体、agents-ext に ListDirectoryTool などの組み込みツールが入っている。

Main.kt

val executor = simpleOpenAIExecutor(System.getenv("OPENAI_API_KEY"))

val agent = AIAgent(
    promptExecutor = executor,
    llmModel = OpenAIModels.Chat.GPT4_1Nano,
    toolRegistry = ToolRegistry {
        tool(ListDirectoryTool(JVMFileSystemProvider.ReadOnly))
        tool(ReadFileTool(JVMFileSystemProvider.ReadOnly))
        tool(RegexSearchTool(JVMFileSystemProvider.ReadOnly))
        tools(ClaudeCodeTools())
    },
    systemPrompt = """
        You are an orchestrator agent working on a local checkout of a project.
        You are given the absolute path to that checkout and a task.

        You may peek at the repo yourself with the read-only tools (list directory, read file,
        regex search), but the actual investigation or code work on the repo should be delegated
        to the run_claude_code tool, which runs the real Claude Code CLI non-interactively against
        the given repo path and returns its JSON result.

        Once you have Claude Code's result, process it and produce a final concise answer/report
        for the original task, citing what run_claude_code returned.
    """.trimIndent(),
    strategy = singleRunStrategy(),
    maxIterations = 100
) {
    handleEvents {
        onToolCallStarting { ctx ->
            println("Tool '${ctx.toolName}' called with args: ${ctx.toolArgs.toString().take(100)}")
        }
    }
}

suspend fun main(args: Array<String>) {
    if (args.size < 2) {
        println("Usage: <absolute_path_to_repo> <task>")
        return
    }

    val path = args[0]
    val task = args.drop(1).joinToString(" ")
    val input = "Project absolute path: $path\n\n## Task\n$task"
    try {
        val result = agent.run(input)
        println("\n=== Answer ===\n$result")
    } finally {
        executor.close()
    }
}

オーケストレータには読み取り専用ツールを3つと、run_claude_code を持たせている。システムプロンプトで「自分で全部読まずに委譲しろ」と書いているが、これは @LLMDescription 側にも同じ趣旨を書いて二重に押している。片方だけだと、オーケストレータが自分で ReadFileTool を延々叩き続けることがあった。

実行すると以下みたいなログが出る

Tool 'run_claude_code' called with args: {repoPath=/path/to/target-repo, task=Summarize the testing st
(数十秒〜数分)

=== Answer ===
(Claudeの調査結果をオーケストレータが要約したもの)

何が嬉しいのか

  • Agentの動きをKoogの設計に則って細かく調整できる
  • コードの探索や生成はそれが得意なAgentに委譲できる
  • github actionに載せると他レポ探索してなんかするってことができそう
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?