🦁

Mastraで作る簡単コードレビューAIエージェント入門 【ハンズオン】

に公開
2025/12/14

この記事では、Mastra を使って「コードを入力するとレビューしてくれる AI エージェント」を作ります。
といっても、これは初心者向けのハンズオンなので、難しいことは一切しません。
内容的には初心者向けのめっちゃ簡単なものです。

コードは以下においてあります

https://github.com/karamage/mastra-code-review-agent

この記事の対象読者

  • Mastra に興味はあるが、何から作ればいいかわからない人
  • AIエージェントを業務(コードレビュー)に使ってみたい人
  • TypeScript / Node.js の基本がわかる人

この記事で作るもの

Code Reviewer Bot という AI エージェントを作ります。

このエージェントは以下のことをします。

  • ソースコードを入力するとレビューを返す(ただ、それだけ。シンプル)
  • バグの可能性、可読性、設計改善点を指摘
  • 初心者にもわかる言葉で説明する

前提環境

  • Node.js v20 以上
  • Mastra プロジェクトが初期化済み
  • OpenAI などの LLM API キーを設定済み

Mastra のセットアップ自体は本記事では省略します。

前準備

mkdir mastra-code-review-agent
cd mastra-code-review-agent
npm init
npm add @mastra/core
npm add @ai-sdk/openai

npm install -D tsx

※ .env にOpenAI APIキーを環境変数に設定してください:
(.envは、GitHubにアップロードしないでください。必ず.gitignoreしてください)

OPENAI_API_KEY='your-api-key-here'

エージェントの設計

まずは、どんなエージェントを作るかを決めます。

  • 名前: Code Reviewer Bot
  • 役割: シニアエンジニアとしてコードレビューを行う
  • 出力: 改善点を丁寧に説明

Mastra では、この「役割」を instructions として定義します。

エージェントを定義する

src/mastra/agents/codeReviewAgent.ts

import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";

export const codeReviewAgent = new Agent({
  name: "code-review-agent",
  instructions: `
You are a senior software engineer.
Review the given code and provide:
- Potential bugs
- Readability improvements
- Design and architectural suggestions

Explain your feedback clearly and politely.
`,
  model: openai("gpt-4o-mini"),
});

ここでは以下を定義しています。

  • name: エージェントの識別子
  • instructions: エージェントの人格・役割
  • model: 使用する LLM

Mastra にエージェントを登録する

次に、Mastra のエントリーポイントにエージェントを登録します。

src/mastra/index.ts

import { Mastra } from "@mastra/core";
import { codeReviewAgent } from "./agents/codeReviewAgent";

export const mastra = new Mastra({
  agents: { codeReviewAgent },
});

これで Mastra から codeReviewAgent を利用できるようになります。

シンプルにコードレビューしてみる

まずは最も基本的な使い方です。

src/index.ts

import { codeReviewAgent } from "./mastra/agents/codeReviewAgent";

async function main() {
  const code = `
function getUserName(user) {
  if (user) {
    return user.name;
  }
}
`;

  const query = `Please review the following code:\n${code}`;

  const response = await codeReviewAgent.generate([
    { role: "user", content: query },
  ]);

  console.log("\nCode Reviewer Bot:\n");
  console.log(response.text);
}

main();

実行すると、コードに対するレビューコメントが返ってきます。

package.json

  "scripts": {
    "start": "tsx src/index.ts",
    "dev": "tsx watch src/index.ts",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
npm start

出力例

❯ npm start

> mastra-code-review-agent@1.0.0 start
> tsx src/index.ts

code to review:

function getUserName(user) {
  if (user) {
    return user.name;
  }
}


Code Reviewer Bot:

Thank you for sharing the code snippet. Here’s a review that covers potential bugs, readability improvements, and design suggestions:

### Potential Bugs
1. **Undefined Return Value**: If the `user` object is falsy (e.g., `null`, `undefined`, or an empty object), the function will return `undefined`. This might not be the intended behavior. It would be better to handle this case explicitly.

2. **Missing Property Check**: The code assumes that if `user` is truthy, it will have a `name` property. If `user` is an object but does not have a `name` property, it will return `undefined`, which might lead to unexpected behavior elsewhere in the code.

### Readability Improvements
1. **Explicit Return for Falsy Cases**: Consider returning a default value or an explicit message when the `user` is falsy. This can improve the clarity of the function's intent.

2. **Descriptive Function Name**: The function name `getUserName` is clear, but you might want to consider renaming it to something like `extractUserName` to indicate that it extracts the name from a user object.

3. **Use of Optional Chaining**: If you are using a modern JavaScript environment, you can use optional chaining to simplify the code.

### Design and Architectural Suggestions
1. **Type Checking**: If this function is part of a larger codebase, consider adding type checking (using TypeScript or JSDoc comments) to ensure that the `user` parameter is indeed an object.

2. **Error Handling**: Depending on the context in which this function is used, you might want to throw an error or return a specific value if the input is not valid.

3. **Documentation**: Adding comments or documentation to explain the function's purpose, parameters, and return value can be beneficial for future maintainers.

### Revised Code Example
Here’s a revised version of the function incorporating the suggestions:

```javascript
/**
 * Extracts the name from a user object.
 * @param {Object} user - The user object.
 * @returns {string} The user's name or a default message if not available.
 */
function extractUserName(user) {
  if (user && typeof user === 'object') {
    return user.name || 'Name not available';
  }
  return 'User not provided';
}
```

### Summary
The original function is a good start, but it can be improved in terms of handling edge cases, readability, and maintainability. By implementing the suggestions above, you can create a more robust and user-friendly function. Thank you for allowing me to review your code!

ストリーミングでレビュー結果を受け取る

レビューが長くなりそうな場合は、
ストリーミングで逐次表示するのが便利です。

import { codeReviewAgent } from "./mastra/agents/codeReviewAgent";

async function main() {
  const stream = await codeReviewAgent.stream([
    {
      role: "user",
      content: "Review this React component...",
    },
  ]);

  for await (const chunk of stream.textStream) {
    process.stdout.write(chunk);
  }
}

main();

CLI ツールやログ出力との相性がとても良いです。

構造化出力でレビュー結果を扱う

ツール連携や自動処理をしたい場合は、
構造化出力(Structured Output) が役立ちます。

import { z } from "zod";
import { codeReviewAgent } from "./mastra/agents/codeReviewAgent";

const schema = z.object({
  issues: z.array(
    z.object({
      category: z.string(),
      description: z.string(),
      suggestion: z.string(),
    })
  ),
  summary: z.string(),
});

const response = await codeReviewAgent.generate(
  [{ role: "user", content: "Review this code..." }],
  { structuredOutput: { schema } }
);

console.log(response.object);

これにより、レビュー結果を JSON として扱えます。

Mastra をサーバーとして起動する

npx mastra dev

起動後は HTTP API 経由でエージェントを呼び出せます。

POST http://localhost:4111/api/agents/codeReviewAgent/generate

CI や GitHub Actions と連携する場合にも便利です。

まとめ

この記事では、Mastra を使って

  • 実務で使えるコードレビュー AI エージェントを作成
  • シンプルな生成からストリーミング、構造化出力まで体験

しました。

Mastra は「AIに何をさせたいか」を素直にコードで表現できるのが強みです。

次のステップとしては、

  • GitHub PR レビュー自動化
  • Slack 連携
  • 社内向け AI 開発アシスタント

などに発展させるのもおすすめです。

参考リンク

Discussion