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?

freee人事労務MCPをFastMCPで作った〜OAuth2実装とAPIハマりどころ全記録〜

0
Posted at

freee人事労務MCPをFastMCPで作った〜OAuth2実装とAPIハマりどころ全記録〜

概要

Claude Desktopから「今日の勤怠を9時から18時で入力して」と言うだけでfreee人事労務に書き込めるMCPサーバーをFastMCPで作った。

OAuth2のAuthorization Code Flowを自前実装し、freee APIのスキーマで3箇所ハマった記録も含めて残しておく。同じところで詰まる人の時間を節約できれば幸いだ。


なぜ作ったか

2026年5月、AnthropicがClaude for Small Businessをリリースした。QuickBooks・PayPal・HubSpot・Canva・DocuSignなどと連携し、給与計画・月次締め・営業キャンペーンといった業務ワークフローをClaude Coworkから実行できるというものだ。

ただし日本の中小企業が使う freee には対応していない。

そこで取った方針がこうだ。

【現状】
Claude for Small Business
 └── QuickBooks / PayPal / HubSpot ... (freeeはない)

【やりたいこと】
Claude Cowork / Claude Desktop
 └── freee HR MCP(自作)
    └── freee人事労務 API

MCPでfreeeへのアクセスが確立できれば、将来的にCoworkのワークフローからもfreeeに接続できる。まずはMCP単体で動作確認するのが今回の目的だ。

補足: Claude for Small Businessの説明文にある「You approve every step that touches money or customers.(お金や顧客に関わるステップはすべてあなたが承認する)」という設計思想はMCPでも同様に実現できる。


構成

Claude Desktop
 └── freee HR MCP(= OAuth2クライアント)
     ↓ アクセストークン提示
   freee API(= リソースサーバー)
     ↑ 認可
   freee 認可サーバー(accounts.secure.freee.co.jp)

MCPサーバーはlocalhost上のPythonプロセスとして動く。Claude Desktopが起動時に自動で立ち上げてくれる。


1. freeeアプリ登録(OAuth2クライアント登録)

freee Developer Communityでアプリを登録し、client_id と client_secret を取得する。

登録URL

https://app.secure.freee.co.jp/developers/applications

入力項目

項目 値
アプリ名 freee-hr-mcp(任意)
アプリタイプ private(自社内利用)
リダイレクトURI urn:ietf:wg:oauth:2.0:oob

補足: urn:ietf:wg:oauth:2.0:oob はローカル環境用の特殊値だ。認可コードがブラウザ画面に直接表示され、コールバックサーバーが不要になる。

権限設定(最小権限の原則)

今回は自分の勤怠入力だけが目的なので以下のみ有効にした。

権限 読み 書き
従業員 ✅ ―
打刻 ✅ ✅
勤怠 ✅ ✅
給与・賞与・手当 ― ―

給与・賞与は触る必要がないので外す。トークンが万が一漏れたとき被害を最小化するためだ。

下書き保存で client_id と client_secret は発行される。アプリストアへの公開申請は他者に使わせる場合のみ必要だ。


2. プロジェクトセットアップ

cd C:\Users\xxxx\IdeaProjects
mkdir freee-hr-mcp
cd freee-hr-mcp

pyproject.toml

[project]
name = "freee-hr-mcp"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
    "fastmcp>=2.0.0",
    "httpx>=0.27.0",
    "python-dotenv>=1.0.0",
]
uv sync

3. MCPサーバー実装

"""
freee人事労務 MCP サーバー
勤怠の参照・打刻を Claude Desktop から操作できるようにする
"""

import json
import os
import webbrowser
from pathlib import Path

import httpx
from dotenv import load_dotenv
from fastmcp import FastMCP

load_dotenv()

CLIENT_ID = os.getenv("FREEE_CLIENT_ID")
CLIENT_SECRET = os.getenv("FREEE_CLIENT_SECRET")
REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"
TOKEN_FILE = Path(__file__).parent / ".tokens.json"

AUTH_URL = "https://accounts.secure.freee.co.jp/public_api/authorize"
TOKEN_URL = "https://accounts.secure.freee.co.jp/public_api/token"
HR_BASE = "https://api.freee.co.jp/hr"

mcp = FastMCP("freee-hr")


# ── トークン管理 ─────────────────────────────────────

def load_tokens() -> dict | None:
    if TOKEN_FILE.exists():
        return json.loads(TOKEN_FILE.read_text())
    return None


def save_tokens(tokens: dict) -> None:
    TOKEN_FILE.write_text(json.dumps(tokens, indent=2))


def get_auth_url() -> str:
    return (
        f"{AUTH_URL}"
        f"?client_id={CLIENT_ID}"
        f"&redirect_uri={REDIRECT_URI}"
        f"&response_type=code"
        f"&scope=read+write"
        f"&prompt=select_company"
    )


async def exchange_code(code: str) -> dict:
    async with httpx.AsyncClient() as client:
        resp = await client.post(TOKEN_URL, data={
            "grant_type": "authorization_code",
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
            "code": code,
            "redirect_uri": REDIRECT_URI,
        })
        resp.raise_for_status()
        return resp.json()


async def refresh_access_token(refresh_token: str) -> dict:
    async with httpx.AsyncClient() as client:
        resp = await client.post(TOKEN_URL, data={
            "grant_type": "refresh_token",
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
            "refresh_token": refresh_token,
        })
        resp.raise_for_status()
        tokens = resp.json()
        save_tokens(tokens)  # ローテーション対応:必ず保存
        return tokens


async def get_valid_token() -> str:
    tokens = load_tokens()
    if tokens is None:
        raise RuntimeError("未認証です。get_auth_link を実行してください。")
    try:
        tokens = await refresh_access_token(tokens["refresh_token"])
    except Exception:
        raise RuntimeError("トークン更新失敗。再度 get_auth_link を実行してください。")
    return tokens["access_token"]


async def hr_get(path: str, params: dict = None) -> dict:
    token = await get_valid_token()
    async with httpx.AsyncClient() as client:
        resp = await client.get(
            f"{HR_BASE}{path}",
            headers={"Authorization": f"Bearer {token}"},
            params=params or {},
        )
        if not resp.is_success:
            raise RuntimeError(f"HTTP {resp.status_code}: {resp.text}")
        return resp.json()


async def hr_put(path: str, body: dict) -> dict:
    token = await get_valid_token()
    async with httpx.AsyncClient() as client:
        resp = await client.put(
            f"{HR_BASE}{path}",
            headers={"Authorization": f"Bearer {token}"},
            json=body,
        )
        if not resp.is_success:
            raise RuntimeError(f"HTTP {resp.status_code}: {resp.text}")
        return resp.json()


def _add_minutes(time_str: str, minutes: int) -> str:
    h, m = map(int, time_str.split(":"))
    total = h * 60 + m + minutes
    return f"{total // 60:02d}:{total % 60:02d}"


# ── MCP ツール ───────────────────────────────────────

@mcp.tool()
def get_auth_link() -> str:
    """freee認可URLを開く。初回セットアップ時に実行する。"""
    url = get_auth_url()
    webbrowser.open(url)
    return (
        f"ブラウザを開いた。freeeにログインして「許可する」を押してほしい。\n"
        f"認可コードが表示されたら set_auth_code に渡すこと。\n\n認可URL: {url}"
    )


@mcp.tool()
async def set_auth_code(code: str) -> str:
    """認可コードをアクセストークンに交換して保存する。"""
    try:
        tokens = await exchange_code(code)
        save_tokens(tokens)
        return "✅ 認証完了。freee人事労務に接続できる。"
    except Exception as e:
        return f"❌ 認証失敗: {e}"


@mcp.tool()
async def get_me() -> str:
    """ログインユーザーの company_id と employee_id を取得する。"""
    data = await hr_get("/api/v1/users/me")
    lines = ["【ログインユーザー情報】"]
    for c in data.get("companies", []):
        lines.append(f"  事業所: {c.get('name')} (company_id={c.get('id')})")
        lines.append(f"  従業員ID: {c.get('employee_id')}")
        lines.append(f"  権限: {c.get('role')}")
    return "\n".join(lines)


@mcp.tool()
async def get_work_record(employee_id: int, company_id: int, target_date: str) -> str:
    """指定日の勤怠情報を取得する。target_date は YYYY-MM-DD 形式。"""
    data = await hr_get(
        f"/api/v1/employees/{employee_id}/work_records/{target_date}",
        params={"company_id": company_id},
    )
    wr = data.get("work_record", data)
    return (
        f"【{target_date} の勤怠】\n"
        f"  出勤: {wr.get('clock_in_at', '未打刻')}\n"
        f"  退勤: {wr.get('clock_out_at', '未打刻')}\n"
        f"  勤務時間: {wr.get('total_work_mins', 0)} 分\n"
        f"  残業時間: {wr.get('overtime_work_mins', 0)} 分"
    )


@mcp.tool()
async def update_work_record(
    employee_id: int,
    company_id: int,
    target_date: str,
    clock_in_at: str,
    clock_out_at: str,
    break_mins: int = 60,
) -> str:
    """
    勤怠を入力・更新する。
    clock_in_at / clock_out_at は HH:MM 形式(例: 09:00)。
    """
    clock_in = f"{target_date} {clock_in_at}:00"
    clock_out = f"{target_date} {clock_out_at}:00"

    body = {
        "company_id": company_id,
        "work_record_segments": [
            {"clock_in_at": clock_in, "clock_out_at": clock_out}
        ],
    }

    await hr_put(
        f"/api/v1/employees/{employee_id}/work_records/{target_date}",
        body,
    )
    return (
        f"✅ {target_date} の勤怠を更新した\n"
        f"  出勤: {clock_in_at} / 退勤: {clock_out_at} / 休憩: {break_mins}分"
    )


@mcp.tool()
async def get_work_records_month(
    employee_id: int, company_id: int, year: int, month: int
) -> str:
    """指定月の勤怠サマリーを取得する。"""
    data = await hr_get(
        f"/api/v1/employees/{employee_id}/work_record_summaries/{year}/{month}",
        params={"company_id": company_id},
    )
    s = data.get("work_record_summary", data)
    total = s.get("total_work_mins", 0)
    overtime = s.get("total_overtime_work_mins", 0)
    return (
        f"【{year}年{month}月 勤怠サマリー】\n"
        f"  総勤務時間: {total // 60}時間{total % 60}分\n"
        f"  総残業時間: {overtime // 60}時間{overtime % 60}分"
    )


if __name__ == "__main__":
    mcp.run()

4. Claude Desktop設定

%APPDATA%\Claude\claude_desktop_config.json の mcpServers に追記する。

{
  "mcpServers": {
    "freee-hr": {
      "command": "uv",
      "args": [
        "run",
        "--project",
        "C:\\Users\\xxxxxx\\IdeaProjects\\freee-hr-mcp",
        "python",
        "C:\\Users\\xxxxxxx\\IdeaProjects\\freee-hr-mcp\\server.py"
      ],
      "env": {
        "FREEE_CLIENT_ID": "your_client_id",
        "FREEE_CLIENT_SECRET": "your_client_secret"
      }
    }
  }
}

Claude Desktopを再起動すれば freee-hr MCPが接続される。


5. 初回認証(1回だけ)

Claude Desktopのチャットで以下を実行する。

get_auth_link を実行して

ブラウザが開き、freeeのログイン→許可画面が表示される。「許可する」を押すと認可コードが画面に表示されるので:

set_auth_code でコード [表示されたコード] を登録して

.tokens.json が生成されれば認証完了だ。以降はリフレッシュトークンで自動更新される。


6. ハマりどころ3連発

① エラー詳細が消えていた

最初の実装では raise_for_status() だけ書いていた。

# ❌ ダメな実装:freeeのエラーメッセージが消える
resp.raise_for_status()

これだと 400 Bad Request しかわからず、freeeが何を拒否しているのか全くわからない。デバッグが泥沼になった。

# ✅ 正しい実装:エラー本文をそのまま返す
if not resp.is_success:
    raise RuntimeError(f"HTTP {resp.status_code}: {resp.text}")

教訓:外部APIを叩くときは必ずレスポンスボディをエラーメッセージに含めること。

② 日時フォーマットが違った

freee APIのドキュメントをよく読まずにISO8601で送っていた。

# ❌ 間違い:ISO8601形式
clock_in = f"{target_date}T{clock_in_at}:00+09:00"

freee人事労務APIが要求するフォーマットはこうだ。

# ✅ 正しい:スペース区切り・タイムゾーンなし
clock_in = f"{target_date} {clock_in_at}:00"

T もタイムゾーン(+09:00)も不要だ。

③ break_recordsのスキーマが合わなかった

break_records を含めると400エラーが返り続けた。原因は2024年6月にfreeeが複数回出退勤に対応した際、リクエストスキーマが変わったことだ。

現時点では work_record_segments に出退勤を入れ、break_records は含めない最小構成が安定して動く。

body = {
    "company_id": company_id,
    "work_record_segments": [
        {"clock_in_at": clock_in, "clock_out_at": clock_out}
    ],
}

7. 使い方

接続後はClaude Desktopで自然言語で操作できる。

今日の勤怠を9時から18時で入力して
今月の勤怠サマリーを見せて
5月11日から14日まで全部9時〜18時で入力して

Claude が get_me で employee_id と company_id を取得し、update_work_record を呼ぶ一連の流れを自動でやってくれる。


まとめ

  • freee人事労務はPublic APIがあり、OAuth2 Authorization Code Flowで接続できる
  • FastMCP + httpx で比較的シンプルに実装できる
  • エラーボディを握り潰さない・日時はスペース区切り・work_record_segments を使う の3点が今回のハマりどころだった
  • 勉強してきたOAuth2がそのまま実地で動く題材として最適だ

freee会計API版や、複数従業員の勤怠管理への拡張も面白そうだ。

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?