Moodle Web Servicesのロゴ

Moodle Web Services

コミュニティ
SaadRahman01
moodle-web-services

Use when adding/calling Moodle web services or external functions — db/services.php, classes/external/, REST/SOAP/AJAX protocols, tokens, capabilities, parameters/returns schemas, file uploads, and rate limiting.

概要

公開者SaadRahman01
リポジトリclaude-moodle-dev
スキル名moodle-web-services
スター
42
フォーク
7
同梱ファイル
指示のみ
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    SaadRahman01がGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Moodle Web Services」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-web-services
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/SaadRahman01/claude-moodle-dev.git /tmp/claude-moodle-dev
mkdir -p .claude/skills
cp -r /tmp/claude-moodle-dev/skills/moodle-web-services .claude/skills/moodle-web-services
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでMoodle Web Servicesを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にMoodle Web Servicesを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Moodle Web Servicesは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

Moodle Web Services

Overview

Moodle exposes plugin functions as web services via db/services.php + classes/external/<fn>.php. Same function is callable as REST, AJAX, SOAP, or XMLRPC. Authentication is token-based for external clients, session-based for AJAX. All inputs/outputs are typed via external_value / external_single_structure / external_multiple_structure.

When to Use

  • Adding a function callable from mobile app, AMD JS, or external system
  • Defining a service (bundle of functions) for an external client
  • Issuing/managing tokens
  • Returning files via web service
  • Debugging "Invalid response value" or "Missing required parameter"

Skip when: building UI-only PHP (no remote callers) — use moodle-plugin-development.

File layout

<plugin>/
  db/services.php                                # function + service definitions
  classes/external/get_items.php                 # one file per external function
  classes/external/get_items_returns.php         # (optional) split returns
  lang/en/<component>.php                        # service descriptions

db/services.php

php
<?php
defined('MOODLE_INTERNAL') || die();

$functions = [
    'local_example_get_items' => [
        'classname'    => 'local_example\external\get_items',
        'methodname'   => 'execute',                // default: 'execute'
        'description'  => 'Return items in a course',
        'type'         => 'read',                   // 'read' or 'write'
        'ajax'         => true,                     // callable from core/ajax
        'capabilities' => 'local/example:view',     // checked in addition to per-method checks
        'services'     => [MOODLE_OFFICIAL_MOBILE_SERVICE], // expose to mobile
    ],
    'local_example_mark_present' => [
        'classname'    => 'local_example\external\mark_present',
        'description'  => 'Mark a user present',
        'type'         => 'write',
        'ajax'         => true,
        'capabilities' => 'local/example:mark',
    ],
];

$services = [
    'Example REST API' => [
        'functions'         => array_keys($functions),
        'restrictedusers'   => 1,        // require explicit user assignment
        'enabled'           => 1,
        'shortname'         => 'local_example_api',
        'downloadfiles'     => 1,
        'uploadfiles'       => 0,
    ],
];

After editing: bump version.php, run php admin/cli/upgrade.php.

External function class

php
<?php
namespace local_example\external;
defined('MOODLE_INTERNAL') || die();

use core_external\external_api;
use core_external\external_function_parameters;
use core_external\external_value;
use core_external\external_single_structure;
use core_external\external_multiple_structure;

class get_items extends external_api {

    public static function execute_parameters(): external_function_parameters {
        return new external_function_parameters([
            'courseid' => new external_value(PARAM_INT, 'Course ID'),
            'limit'    => new external_value(PARAM_INT, 'Max items', VALUE_DEFAULT, 50),
        ]);
    }

    public static function execute(int $courseid, int $limit = 50): array {
        global $DB, $USER;

        // 1. Validate params (re-runs schema, normalizes types)
        $params = self::validate_parameters(self::execute_parameters(), [
            'courseid' => $courseid,
            'limit'    => $limit,
        ]);

        // 2. Validate context + capability
        $context = \context_course::instance($params['courseid']);
        self::validate_context($context);
        require_capability('local/example:view', $context);

        // 3. Business logic
        $rows = $DB->get_records('local_example_items',
            ['courseid' => $params['courseid']], 'timecreated DESC', '*', 0, $params['limit']);

        return array_values(array_map(fn($r) => [
            'id'   => (int)$r->id,
            'name' => format_string($r->name, true, ['context' => $context]),
            'time' => (int)$r->timecreated,
        ], $rows));
    }

    public static function execute_returns(): external_multiple_structure {
        return new external_multiple_structure(
            new external_single_structure([
                'id'   => new external_value(PARAM_INT, 'ID'),
                'name' => new external_value(PARAM_TEXT, 'Name'),
                'time' => new external_value(PARAM_INT, 'Created timestamp'),
            ])
        );
    }
}

Required ordering inside execute():

  1. validate_parameters()
  2. validate_context()
  3. require_capability()
  4. business logic
  5. format output (format_string, format_text with context)

Skipping any of (1)-(3) is a security bug.

Moodle version notes

MoodleNamespace
4.2+core_external\external_api (etc.)
≤ 4.1bare external_api (no namespace)

For 4.2+ compatibility wrappers, see lib/classes/external/.

Parameter types (PARAM_*)

ConstantUse
PARAM_INTIntegers
PARAM_FLOATDecimals
PARAM_BOOLtrue/false
PARAM_TEXTPlain text (strips tags)
PARAM_RAWUntrusted text — use only if you re-format on output
PARAM_NOTAGSStrips tags, keeps entities
PARAM_CLEANHTMLSanitized HTML
PARAM_ALPHANUMa-zA-Z0-9
PARAM_ALPHAa-zA-Z
PARAM_USERNAMEValidates Moodle username
PARAM_EMAILValidates email
PARAM_URLValidates URL
PARAM_FILEFilename (no path)
PARAM_PATHPath (no ..)
PARAM_COMPONENTfrankenstyle (local_example)
PARAM_CAPABILITYlocal/example:view
PARAM_PLUGIN<name> part
PARAM_AREAFile area names
PARAM_BASE64Base64

VALUE_REQUIRED (default), VALUE_OPTIONAL (omit from response if null), VALUE_DEFAULT (with default).

Calling from REST

bash
TOKEN=abcdef0123456789
SITE=https://moodle.example.com

curl -X POST "$SITE/webservice/rest/server.php" \
  -d "wstoken=$TOKEN" \
  -d "moodlewsrestformat=json" \
  -d "wsfunction=local_example_get_items" \
  -d "courseid=5" \
  -d "limit=10"

Response on error:

json
{"exception":"invalid_parameter_exception","errorcode":"invalidparameter","message":"..."}

Calling from AJAX (browser)

javascript
import Ajax from 'core/ajax';

const [items] = await Ajax.call([{
    methodname: 'local_example_get_items',
    args: {courseid: 5, limit: 10},
}]);

Requires 'ajax' => true in db/services.php. Session cookie auths; no token needed.

Token issuance

bash
# Site admin > Server > Web services > Manage tokens
# or programmatically:
php
$service = $DB->get_record('external_services', ['shortname' => 'local_example_api']);
$token = \core_external\util::generate_token(
    EXTERNAL_TOKEN_PERMANENT,
    $service,
    $userid,
    \context_system::instance()
);

File uploads via web service

  1. Upload to draft area: POST /webservice/upload.php?token=$T&filearea=draft&itemid=0
  2. Returns itemid
  3. Pass that itemid to your function via a PARAM_INT param
  4. In execute(), move from draft to plugin area:
php
file_save_draft_area_files($params['draftitemid'], $context->id,
    'local_example', 'attachments', $itemid,
    ['subdirs' => 0, 'maxfiles' => 5]);

Service must have uploadfiles => 1.

File downloads

Set downloadfiles => 1 on service, serve via pluginfile.php. Token-authed clients append ?token=$T to pluginfile URLs.

Rate limiting

No built-in per-token rate limit. Options:

  • \core\session\manager::is_loggedinas() checks
  • Custom middleware via lib/setuplib.php hook
  • Reverse-proxy rate limit (nginx limit_req)

Common Mistakes

MistakeFix
Skipping validate_parameters()Always call first — ensures types match schema
Skipping validate_context()Required for capability + permission scoping
Returning unformatted user textRun through format_string() / format_text() with context
Schema mismatch in returnsWrap response with clean_returnvalue in tests
Wrong namespace pre-4.2Use external_api bare; for 4.2+ use core_external\external_api
'ajax' => true missing for browser callsCalls fail with accessexception
Not bumping version.php after db/services.php changeService won't register — bump + upgrade
Token user lacks required capabilityrequire_capability fails — assign user to service or grant cap
restrictedusers => 1 but no users assignedSite admin > Server > Web services > Authorised users
MOODLE_OFFICIAL_MOBILE_SERVICE exposes more than intendedAudit — only add functions safe for mobile app

Testing

php
// tests/external/get_items_test.php
$this->setUser($user);
$result = get_items::execute($course->id, 10);
$result = external_api::clean_returnvalue(get_items::execute_returns(), $result);
$this->assertCount(2, $result);

clean_returnvalue is mandatory — catches return schema bugs.

References

よくある質問

AIスキル「Moodle Web Services」では何ができますか?

Use when adding/calling Moodle web services or external functions — db/services.php, classes/external/, REST/SOAP/AJAX protocols, tokens, capabilities, parameters/returns schemas, file uploads, and rate limiting.

TypingMindでMoodle Web Servicesを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Moodle Web Servicesはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにMoodle Web Servicesをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-web-servicesを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Moodle Web Servicesを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Moodle Web Servicesで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもMoodle Web Servicesを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Moodle Web Services」は無料ですか?

はい。SaadRahman01がMITライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇