Wednesday, July 01, 2026

Using Oracle SQLcl MCP with Claude Code CLI tool

While SQL Developer for VS Code provides a built-in "one-click" MCP for Copilot, Claude Code requires you to explicitly add the database MCP server (like SQLcl for Oracle or generic SQL servers) using its CLI.

Here are the steps I used to configure it with CC: 

 (1) Download SQLcl 

You may download the latest Oracle SQLcl tool which supports MCP at https://www.oracle.com/database/sqldeveloper/technologies/sqlcl/download/ , current version 26.1.
 
In my case, it was downloaded last year with version 25.2 it is at my local path: C:\users\dsun\sqlcl-latest\sqlcl\bin 

(2) Add the SQL MCP Server In my project directory C:\Users\dsun\ClaudeCode_DBA_Assistant:
PS C:\Users\dsun\ClaudeCode_DBA_Assistant> claude mcp add --transport stdio sqlcl -- C:\users\dsun\sqlcl-latest\sqlcl\bin\sql -mcp
Added stdio MCP server sqlcl with command: C:\users\dsun\sqlcl-latest\sqlcl\bin\sql -mcp to local config
File modified: C:\Users\dsun\.claude.json [project: C:\Users\dsun\ClaudeCode_DBA_Assistant]
(3) Verify the Connection
 
PS C:\Users\dsun\ClaudeCode_DBA_Assistant> claude mcp list
sqlcl: C:\users\dsun\sqlcl-latest\sqlcl\bin\sql -mcp - v Connected
PS C:\Users\dsun\ClaudeCode_DBA_Assistant>

(4) Create a saved connection Note: using -thin is necessary in my environment to avoid error from " thick client "
PS C:\users\dsun\sqlcl-latest\sqlcl\bin> .\sql -thin 'test/"xxzzzzzz"@dbhost1.mycompany.com:1521/testdb'


SQLcl: Release 25.2 Production on Wed Jul 01 07:07:37 2026

Copyright (c) 1982, 2026, Oracle.  All rights reserved.

Last Successful login time: Wed Jul 01 2026 07:07:42 -04:00

Connected to:
Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production
Version 19.28.0.0.0

SQL> conn -save testdb_cc -savepwd
Name: testdb_cc
Connect String: dbhost1.mycompany.com:1521/testdb
User: test
Password: ******
 
(5) Interact with database in CC CLI Using natural language e.g. sqlcl show 10 largest tables in testdb_cc
PS C:\Users\dsun\ClaudeCode_DBA_Assistant> claude
 ¦?¦¦¦?¦   Claude Code v2.1.181
??¦¦¦¦¦??  Haiku 4.5 · API Usage Billing
  ?? ??    ~\ClaudeCode_DBA_Assistant


> sqlcl show 10 largest tables in testdb_cc

  Thought for 3s, called MCP (ctrl+o to expand)

? I'll connect to testdb_cc and query the 10 largest tables using sqlcl.

  Called sqlcl 2 times (ctrl+o to expand)

? Now I'll query the 10 largest tables by size.

  Called sqlcl (ctrl+o to expand)

? Let me check the available columns in DBA_TABLES and use the correct approach.

  Called sqlcl 2 times (ctrl+o to expand)

? Let me use DBA_SEGMENTS instead, which contains the actual allocated space:

  Called sqlcl (ctrl+o to expand)

? Here are the 10 largest tables in testdb_cc:

  +-------------------------------------------------------------------+
  ¦ Owner ¦    Table Name     ¦ Size (GB) ¦ Segment Type ¦ Tablespace ¦
  +-------+-------------------+-----------+--------------+------------¦
  ¦ TEST  ¦ LOGFILE_SYNC_TEST ¦ 57.30     ¦ TABLE        ¦ USERS      ¦
  +-------+-------------------+-----------+--------------+------------¦
  ¦ USER1 ¦ CF1               ¦ 2.06      ¦ TABLE        ¦ IOPS       ¦
  +-------+-------------------+-----------+--------------+------------¦
  ¦ USER3 ¦ CF1               ¦ 2.01      ¦ TABLE        ¦ IOPS       ¦
  +-------+-------------------+-----------+--------------+------------¦
  ¦ USER5 ¦ CF1               ¦ 2.00      ¦ TABLE        ¦ IOPS       ¦
  +-------+-------------------+-----------+--------------+------------¦
  ¦ USER4 ¦ CF1               ¦ 2.00      ¦ TABLE        ¦ IOPS       ¦
  +-------+-------------------+-----------+--------------+------------¦
  ¦ USER7 ¦ CF1               ¦ 2.00      ¦ TABLE        ¦ IOPS       ¦
  +-------+-------------------+-----------+--------------+------------¦
  ¦ USER6 ¦ CF1               ¦ 2.00      ¦ TABLE        ¦ IOPS       ¦
  +-------+-------------------+-----------+--------------+------------¦
  ¦ USER2 ¦ CF1               ¦ 1.99      ¦ TABLE        ¦ IOPS       ¦
  +-------+-------------------+-----------+--------------+------------¦
  ¦ USER8 ¦ CF1               ¦ 1.98      ¦ TABLE        ¦ IOPS       ¦
  +-------+-------------------+-----------+--------------+------------¦
  ¦ TPCC  ¦ STOCK             ¦ 0.18      ¦ TABLE        ¦ TPCC_DATA  ¦
  +-------------------------------------------------------------------+

  Key observations:
  - The TEST.LOGFILE_SYNC_TEST table dominates storage at 57.3 GB (likely a test/load table)
  - Multiple user schemas (USER1-USER8) have similarly-sized CF1 tables (~2 GB each) in the IOPS tablespace
  - The TPCC.STOCK table is relatively small at 0.18 GB in the TPCC_DATA tablespace

  Would you like to analyze space usage patterns, identify candidates for cleanup, or investigate the purposes of these large tables?

? Worked for 25s

? recap: Identified 10 largest tables in testdb_cc: TEST.LOGFILE_SYNC_TEST dominates at 57.3GB, followed by USER schemas' CF1 tables at ~2GB each. Awaiting next diagnostic step. (disable recaps in /config)


In summary, this post demonstrates how to connect Oracle SQLcl to the Claude Code CLI tool using the Model Context Protocol (MCP). By registering SQLcl as an MCP server and saving database credentials locally, users can query Oracle databases using natural language commands directly within the Claude Code interface. In the provided walkthrough, Claude successfully identifies the 10 largest tables in an Oracle 19c database by dynamically inspecting data dictionary views like DBA_SEGMENTS.

Monday, October 06, 2025

AI Engineer - DB Diagnostic AI Agent through SQLcl MCP

In this post, I demonstrate how a basic LangGraph ReAct agent can work with Oracle MCP Server for Oracle Database. This is just a one of the proof-of-concept steps toward developing an Oracle database diagnostic AI agent application. 

The Model Context Protocol (MCP) lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. Think of it like a web API, but specifically designed for LLM interactions. The Oracle MCP Server for Oracle Database is Oracle's implementation of the Model Context Protocol (MCP). It comes with SQLcl 25.2 version, which stands for the SQL Developer Command Line tool, a Java-based command-line interface for Oracle Database. The Key functions and features of the Oracle MCP Server for Oracle Database are summarized as follows: 


Direct AI-Database Integration:

It allows AI assistants to directly connect to, query, and analyze data within Oracle databases, eliminating the need for manual SQL generation and execution by users. This enables "agentic workflows" where AI can autonomously implement its recommendations. 


Leverages Oracle SQLcl: 

The MCP Server integrates through Oracle SQLcl, extending its capabilities to support MCP-based communication. This allows AI applications to access database operations through a defined set of tools and utilize preconfigured SQLcl connections. 


Natural Language Interaction: 

AI clients can use natural language to perform various database operations, including executing SQL queries, invoking PL/SQL procedures, exploring the data dictionary, and running SQLcl-specific commands. 


Enhanced Security: 

It leverages existing Oracle Database security frameworks, ensuring that AI access adheres to established organizational security policies and provides transparency and traceability of AI-driven actions within the database. 


Broad Compatibility:

The MCP Server works with various Oracle Database versions (e.g., 19c to 23ai) and can be deployed in diverse environments, including on-premises, hyperscalers (Azure, AWS, Google, OCI), and even on local machines.


Facilitates Conversational Databases:

It represents a significant step towards "conversational databases," where AI can interact with structured data in a more intuitive and efficient manner, streamlining tasks like data retrieval, analysis, and report generation. 


In my dev env, I've first set up the MCP server and created a saved connection as follows: 


  • Software needed: 


 (a) I unzip'ed the latest sqlcl (25.2.2) in the directory ~/denis/python_proj/sqlcl/bin 

 (b) I placed Oracle instant client at ~/denis/python_proj/instantclient_23_9 

 (c) JDK 21 at ~/denis/python_proj/jdk-21.0.8 


  • Set up environment variables



    (denis_venv) [dsun001@linuxhost006 python_proj]$ cat setup_mcp_env_dsun001.sh
    export JAVA_HOME=/path/to/oracle/denis/python_proj/jdk-21.0.8
    export PATH=$JAVA_HOME/bin:$PATH
    export ORACLE_HOME=/path/to/oracle/denis/python_proj/instantclient_23_9

    cd /path/to/oracle/denis/python_proj/sqlcl/bin

Create a saved connection

    cd /path/to/oracle/denis/python_proj/sqlcl/bin

    (denis_venv) [dsun001@linuxhost006 bin]$ ./sql test/xxxxx@tpsghvvnsdp001scan.verizon.com:1521/test1db

    SQLcl: Release 25.2 Production on Fri Oct 03 18:29:05 2025

    Copyright (c) 1982, 2025, Oracle.  All rights reserved.

    Last Successful login time: Fri Oct 03 2025 18:29:06 -04:00

    Connected to:
    Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production
    Version 19.12.0.0.0

    SQL> conn -save test1db_mcp -savepwd
    Name: test1db_mcp
    Connect String: tpsghvvnsdp001scan.verizon.com:1521/test1db
    User: test
    Password: ******

  • Test the connection cd /path/to/oracle/denis/python_proj/sqlcl/bin (denis_venv) [dsun001@linuxhost006 bin]$ ./sql -name test1db_mcp SQLcl: Release 25.2 Production on Fri Oct 03 18:33:17 2025 Copyright (c) 1982, 2025, Oracle. All rights reserved. Connected to: Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production Version 19.12.0.0.0 SQL> Start MCP server and misc commands cd /path/to/oracle/denis/python_proj/sqlcl/bin (denis_venv) [dsun001@linuxhost006 bin]$ ./sql -mcp ---------- MCP SERVER STARTUP ---------- MCP Server started successfully on Fri Oct 03 18:34:11 EDT 2025 $ ./sql /nolog SQL> connect -name test1db_mcp Connected. SQL> connect -name test1db_mcp Connected. SQL> connmgr list . +-- test1db_mcp SQL> connmgr show test1db_mcp Name: test1db_mcp Connect String: linuxhost001scan.mycompany.com:1521/test1db User: test Password: ******

A LangGraph ReAct agent is an AI agent built using the LangGraph framework that implements the ReAct (Reasoning + Acting) paradigm. Here's a breakdown of its key components and how it operates: 


ReAct Framework: 

This paradigm, inspired by human problem-solving, combines reasoning and action-taking. The agent iteratively performs the following steps: 

Thought: The Large Language Model (LLM) reasons about the user query or current state, determining the next logical step. 

Action: The LLM decides which tool to use (if any) and how to use it based on its reasoning.

Observation: The agent executes the chosen tool and observes the result, which then informs the next "Thought" step.This loop continues until the agent reaches a final answer or a predefined stop condition. 


With the help of Copilot and some sample code googled from web, I was able to quickly stand up a Python program to interact with the MCP, do some basic testing. This gives me greater confidence to explore further in the AI agent world, the program called diagagent, the code repo of the project can be found here: https://github.com/denissun/DBRE-YDS/tree/main/diagagent


One interesting conversation history can be seen in the following section: 

You can see that the agent can correctly identify the problem area of a test db running some testing workload, which intentionally did not use correct index .

(denis_venv) [dsun001@linuxhost006 diagagent]$ python app_cli.py


WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
E0000 00:00:1759598621.279845 1613965 alts_credentials.cc:93] ALTS creds ignored. Not running on GCP and untrusted ALTS is not enabled.
============================================================
?? Diagnostic AI Agent through SQLcl MCP  - Command Line Interface
============================================================
Ask natural language questions about your Oracle database.
Type 'quit', 'exit', or 'q' to exit the program.
============================================================

?? Available Commands:
  help, h          - Show this help message
  quit, exit, q    - Exit the program
  clear, cls       - Clear the screen
  reset, restart   - Reset session and conversation history
  test             - Test SQLcl MCP connection

?? Example queries:
  • Connect to MYDB database
  • How many employees earn more than 10000?
  • Show me the top 5 customers by revenue
  • What tables are available in the database?
  • Create a summary report of sales by region

?? Database Connection:
  The agent maintains your database connection and conversation context.
  Once connected, you don't need to reconnect for subsequent queries.
  Use 'reset' if you need to start fresh or change connections.


------------------------------------------------------------
?? Enter your question: list connections

?? Processing: list connections
------------------------------------------------------------
?? Initializing persistent MCP session (single-run)...
?? Initializing MCP protocol handshake...
---------- MCP SERVER STARTUP ----------
MCP Server started successfully on Sat Oct 04 13:23:45 EDT 2025
Press Ctrl+C to stop the server
----------------------------------------
Oct 04, 2025 1:23:46 PM io.modelcontextprotocol.server.McpAsyncServer$AsyncServerImpl lambda$asyncInitializeRequestHandler$5
INFO: Client initialize request - Protocol: 2025-06-18, Capabilities: ClientCapabilities[experimental=null, roots=null, sampling=null], Info: Implementation[name=mcp, version=0.1.0]
Oct 04, 2025 1:23:46 PM io.modelcontextprotocol.server.McpAsyncServer$AsyncServerImpl lambda$asyncInitializeRequestHandler$5
WARNING: Client requested unsupported protocol version: 2025-06-18, so the server will sugggest the 2024-11-05 version instead
?? Loading MCP tools (first time)...
? Loaded 5 tools
? Persistent session & agent ready
?? Processing query with persistent session...
E0000 00:00:1759598626.798840 1613965 alts_credentials.cc:93] ALTS creds ignored. Not running on GCP and untrusted ALTS is not enabled.
? Agent Response:
------------------------------------------------------------
connect to test1db_mcp

------------------------------------------------------------
?? Enter your question: connect to test1db_mcp

?? Processing: connect to test1db_mcp
------------------------------------------------------------
?? Processing query with persistent session...
? Agent Response:
------------------------------------------------------------
show tables

------------------------------------------------------------
?? Enter your question: any performance issues?

?? Processing: any performance issues?
------------------------------------------------------------
?? Processing query with persistent session...
? Agent Response:
------------------------------------------------------------
I cannot directly detect performance issues. However, I can run SQL queries to gather information that can help identify potential problems. What metrics or aspects of database performance are you most interested in? For example, I can check:

1.  **Long-running queries:** Identify queries that take a long time to execute.
2.  **High CPU usage:** Determine if any particular queries are consuming excessive CPU resources.
3.  **Index usage:** Analyze whether indexes are being used effectively.
4.  **Wait events:** Investigate what events are causing sessions to wait.

Please specify what you would like me to check, and I will generate the appropriate SQL queries.

------------------------------------------------------------
?? Enter your question: Wait events

?? Processing: Wait events
------------------------------------------------------------
?? Processing query with persistent session...
? Agent Response:
------------------------------------------------------------
The top wait events are:

*   rdbms ipc message
*   PX Idle Wait
*   Space Manager: slave idle wait
*   pmon timer
*   class slave wait
*   SQL\*Net message from client
*   wait for unread message on broadcast channel
*   watchdog main loop
*   ges remote message
*   gcs yield cpu

These wait events can indicate different types of performance bottlenecks. For example, "SQL\*Net message from client" might suggest network issues or slow client processing, while "PX Idle Wait" is often related to parallel execution. "rdbms ipc message" is related to inter-process communication.

Do you want to investigate any of these further? For example, I can provide more details on "SQL\*Net message from client".

------------------------------------------------------------
?? Enter your question: any long running sql?

?? Processing: any long running sql?
------------------------------------------------------------
?? Processing query with persistent session...
? Agent Response:
------------------------------------------------------------
Here are the top 10 long-running SQL statements, based on elapsed time:

1.  **SQL_ID: anagjqfhrc7v3**
    *   Elapsed Time: 99817854477 (likely microseconds)
    *   Module: SQL\*Plus
    *   SQL Text: A PL/SQL block that includes a loop with `DBMS_LOCK.SLEEP(1)`, selects from `big_table`, and conditionally updates `big_table`.

2.  **SQL_ID: anagjqfhrc7v3**
    *   Elapsed Time: 83189131874 (likely microseconds)
    *   Module: SQL\*Plus
    *   SQL Text:  Same PL/SQL block as above.

3.  **SQL_ID: fa1tzyz2rg3h0**
    *   Elapsed Time: 70702684556 (likely microseconds)
    *   Module: SQL\*Plus
    *   SQL Text: `UPDATE BIG_TABLE SET OBJECT_NAME =LOWER(OBJECT_NAME) WHERE TRUNC(LAST_DDL_TIME) BETWEEN SYSDATE-30 AND SYSDATE -25`

4.  **SQL_ID: anagjqfhrc7v3**
    *   Elapsed Time: 38188454383 (likely microseconds)
    *   Module: SQL\*Plus
    *   SQL Text: Same PL/SQL block as above.

5.  **SQL_ID: fa1tzyz2rg3h0**
    *   Elapsed Time: 37070296233 (likely microseconds)
    *   Module: SQL\*Plus
    *   SQL Text: `UPDATE BIG_TABLE SET OBJECT_NAME =LOWER(OBJECT_NAME) WHERE TRUNC(LAST_DDL_TIME) BETWEEN SYSDATE-30 AND SYSDATE -25`

6.  **SQL_ID: 05jnwzh1jfb9y**
    *   Elapsed Time: 12756757422 (likely microseconds)
    *   Module: SQL\*Plus
    *   SQL Text: `SELECT MAX(OBJECT_NAME) FROM BIG_TABLE WHERE TRUNC(LAST_DDL_TIME) = TRUNC(SYSDATE-:B1 )`

7.  **SQL_ID: 05jnwzh1jfb9y**
    *   Elapsed Time: 6706007056 (likely microseconds)
    *   Module: SQL\*Plus
    *   SQL Text: `SELECT MAX(OBJECT_NAME) FROM BIG_TABLE WHERE TRUNC(LAST_DDL_TIME) = TRUNC(SYSDATE-:B1 )`

8.  **SQL_ID: 6hnhqahphpk8n**
    *   Elapsed Time: 5102794792 (likely microseconds)
    *   Module:
    *   SQL Text: `select free_mb from v$asm_diskgroup_stat where name=:1`

9.  **SQL_ID: 6hnhqahphpk8n**
    *   Elapsed Time: 3787833663 (likely microseconds)
    *   Module:
    *   SQL Text: `select free_mb from v$asm_diskgroup_stat where name=:1`

10. **SQL_ID: fhf8upax5cxsz**
    *   Elapsed Time: 3021389633 (likely microseconds)
    *   Module:
    *   SQL Text: `BEGIN sys.dbms_auto_report_internal.i_save_report (:rep_ref, :snap_id, :pr_class,:rep_id, :suc); END;`

It appears that the PL/SQL block (SQL\_ID: anagjqfhrc7v3) and the update statement (SQL\_ID: fa1tzyz2rg3h0) against `BIG_TABLE` are the most time-consuming. The select statement (SQL\_ID: 05jnwzh1jfb9y) against `BIG_TABLE` also appears in the list. You should investigate these further. It seems like the PL/SQL code is deliberately slowing down via `DBMS_LOCK.SLEEP(1)`.

Do you want to investigate any of these SQL IDs further? For example, I can explain the execution plan for the update statement.

------------------------------------------------------------
?? Enter your question: can you suggest how to tune fa1tzyz2rg3h0?

?? Processing: can you suggest how to tune fa1tzyz2rg3h0?
------------------------------------------------------------
?? Processing query with persistent session...
? Agent Response:
------------------------------------------------------------
The SQL ID `fa1tzyz2rg3h0` corresponds to the following SQL statement:

`UPDATE BIG_TABLE SET OBJECT_NAME =LOWER(OBJECT_NAME) WHERE TRUNC(LAST_DDL_TIME) BETWEEN SYSDATE-30 AND SYSDATE -25`

Here's a breakdown of potential tuning strategies:

**1. Indexing:**

*   **LAST_DDL_TIME:**  The `TRUNC(LAST_DDL_TIME)` in the `WHERE` clause is likely preventing efficient index usage. If `LAST_DDL_TIME` is a `DATE` or `TIMESTAMP` column, create an index on `LAST_DDL_TIME`. The database might then be able to use an index range scan.
    ```sql
    CREATE INDEX idx_big_table_last_ddl_time ON BIG_TABLE (LAST_DDL_TIME);
    ```

**2. Partitioning:**

*   If `BIG_TABLE` is large and `LAST_DDL_TIME` represents a natural partitioning key (e.g., daily or weekly), consider partitioning the table by range on `LAST_DDL_TIME`. This can significantly improve the performance of queries that filter on this column.

**3. Statistics:**

*   Ensure that the table statistics are up-to-date. This allows the optimizer to make informed decisions about the execution plan.
    ```sql
    EXEC DBMS_STATS.GATHER_TABLE_STATS(ownname => 'SCHEMA_NAME', tabname => 'BIG_TABLE', estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE, method_opt => 'FOR ALL COLUMNS SIZE AUTO');
    ```
    Replace `SCHEMA_NAME` with the actual schema name.

**4. Eliminate `TRUNC`:**

*   The `TRUNC(LAST_DDL_TIME)` is problematic for index usage. Rewrite the query to avoid truncating the date. For example:

    ```sql
    UPDATE BIG_TABLE
    SET OBJECT_NAME = LOWER(OBJECT_NAME)
    WHERE LAST_DDL_TIME >= TRUNC(SYSDATE - 30)
      AND LAST_DDL_TIME < TRUNC(SYSDATE - 24); -- Corrected the upper bound
    ```

**5. Case-Insensitive Collation:**

*   If you are using a case-insensitive collation, the `LOWER` function might be redundant. Check the collation of the `OBJECT_NAME` column. If it's already case-insensitive, removing `LOWER` might save some CPU cycles.

**6. Batch Processing (If Applicable):**

*   If this update is performed frequently, consider batching the updates into larger transactions. This reduces the overhead associated with transaction management.

**7. Check for Blocking:**

*   Ensure that other sessions are not blocking this update statement. Use `v$lock` and `v$session` to identify any blocking issues.

Before implementing any of these changes, it's crucial to:

1.  **Test:** Test the changes in a non-production environment first.
2.  **Explain Plan:** Examine the execution plan before and after the changes to verify that the optimizer is using the index and that the plan is more efficient.  You can get the execution plan using `EXPLAIN PLAN FOR` followed by the SQL statement, then query the `TABLE(DBMS_XPLAN.DISPLAY)` to view the plan.

Which of these areas would you like to explore further? For example, I can show you how to get the execution plan.


In summary, integrating a LangGraph ReAct agent with Oracle's SQLcl MCP server bridges the gap between natural language interaction and complex database diagnostics. By combining conversational AI with direct, secure access to database performance views, the agent can autonomously navigate metadata, surface performance bottlenecks like unindexed range queries or artificial latencies, and deliver actionable tuning recommendations. This proof-of-concept highlights the strong potential of autonomous AI agents in transforming routine database administration and diagnostic workflows.


Monday, September 29, 2025

AI coding agent : a toy project helps me understand the agentic AI concept a lot

Following the following course :

 


I have been able to complete the AI coding agent project , which really helped me understand agentic AI from a practical point of view. To put the agent to the test, I introduced an intentional bug in a simple Calculator class by setting the operator precedence incorrectly:


class Calculator:
    def __init__(self):
        self.operators = {
            "+": lambda a, b: a + b,
            "-": lambda a, b: a - b,
            "*": lambda a, b: a * b,
            "/": lambda a, b: a / b,
        }
        self.precedence = {
            "+": 3,           # should be 1, set to 3 so 3 + 5 * 2 = 16
            "-": 1,
            "*": 2,
            "/": 2,
        }


As expected, this flaw caused the calculator to fail basic math. For instance, the expression 3 + 5 * 2 returned 16 instead of the correct value of 13:

(venv313) C:\Users\dsun\Denis_files\python_proj\ai_apps\aicodeagent>python calculator\main.py " 3 + 5 * 2 "
{
  "expression": " 3 + 5 * 2 ",
  "result": 16
}

What defines an "agent" is its ability to autonomously use tools and iterate based on its findings. In this setup, the agent was equipped with four primary functions:


available_functions = types.Tool(
    function_declarations=[
        schema_get_files_info,
        schema_get_file_content,
        schema_run_python_file,
        schema_write_file,
    ]
)

The following "conversation" log illustrates the agent's decision-making process as it navigated the codebase and applied the fix automatically: (venv313) C:\Users\dsun\Denis_files\python_proj\ai_apps\aicodeagent>python main.py " 3 + 5 * 2 should not be 16 please fix the code problem under calculator folder"
User: " 3 + 5 * 2 should not be 16 please fix the code problem under calculator folder"
Model: "I want to call get_files_info..."
 - Calling function: get_files_info
Tool: "Here's the result of get_files_info..."
Model: "I want to call get_files_info..."
 - Calling function: get_files_info
Tool: "Here's the result of get_files_info..."
Model: "I want to call get_file_content..."
 - Calling function: get_file_content
Tool: "Here's the result of get_file_content..."
Model: "I want to call get_files_info..."
 - Calling function: get_files_info
Tool: "Here's the result of get_files_info..."
Model: "I want to call get_file_content..."
 - Calling function: get_file_content
Tool: "Here's the result of get_file_content..."
Model: "I want to call write_file..."
 - Calling function: write_file
Tool: "Here's the result of write_file..."
Model: "I want to call run_python_file..."
 - Calling function: run_python_file
Tool: "Here's the result of run_python_file..."
Model: "Great! The output is 13, which means the fix was successful. The calculator now correctly evaluates the expression "3 + 5 * 2".
"

With the agent's intervention complete, the bug was resolved without any manual code editing:
(venv313) C:\Users\dsun\Denis_files\python_proj\ai_apps\aicodeagent>python calculator\main.py " 3 + 5 * 2 "
{
  "expression": " 3 + 5 * 2 ",
  "result": 13
}

In summary,this experiment highlighted the most critical aspect of agentic AI: the feedback loop. By allowing the agent to run code, analyze errors, and rewrite files, we move beyond simple text generation into the realm of autonomous problem-solving. To me, this project was a vital stepping stone in understanding how AI can act as a true collaborator in the development process.

Tuesday, August 05, 2025

PostgreSQL - Sampling pg_stat_activity with pgcheck

I have added a new option (-psas or pg_stat_activity_sampling) to the pgcheck tool, which samples pg_stat_activity at 1-second intervals over a 1-minute duration. This feature generates reports on Average Active Sessions (AAS), top wait events, and top queries, offering a useful alternative to AWS Performance Insight. While it doesn't provide a long-term history of active sessions, it offers a valuable snapshot for immediate troubleshooting. Here is an example of the output under a pgbench workload:

(venv) someip.myco.com:/u01/app/postgres/pgcheck [etsdb] $ pgcheck.py ~/ini/dbaets.ini -psas
Trying to obtain connection info from the configuation file  /opt/oracle/ini/dbaets.ini ...
wait for 1 min ...
#### pg_stat_activity Sampling start from 2019-08-05 12:25:05.535325 to 2019-08-05 12:26:05.657529
# Average Active Session Report #
Average Active Sessions : 4
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# wait event report #
wait_event_type    wait_event     #sessions
-----------------  --------------  ----------
Client             ClientRead     107
Lock               transactionid  78
Lock               tuple          23
None               None           17
IO                 XactSync       15
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Top SQL  report #
query                                                         wait_event     #sessions
---------------------------------------------------           --------------  ----------
UPDATE pgbench_branches SET bbalance = bbalance + 3758 WHERE  ClientRead     32
END;                                                          ClientRead     26
UPDATE pgbench_branches SET bbalance = bbalance + 27 WHERE b  ClientRead     25
UPDATE pgbench_branches SET bbalance = bbalance + 1458 WHERE  ClientRead     24
END;                                                          transactionid  21
UPDATE pgbench_branches SET bbalance = bbalance + 27 WHERE b  transactionid  20
UPDATE pgbench_branches SET bbalance = bbalance + 3758 WHERE  transactionid  19
UPDATE pgbench_branches SET bbalance = bbalance + 1458 WHERE  transactionid  18
UPDATE pgbench_branches SET bbalance = bbalance + 27 WHERE b  None           7
UPDATE pgbench_branches SET bbalance = bbalance + 1458 WHERE  tuple          7
UPDATE pgbench_branches SET bbalance = bbalance + 1458 WHERE  XactSync       7
UPDATE pgbench_branches SET bbalance = bbalance + 27 WHERE b  tuple          6
END;                                                          tuple          5
UPDATE pgbench_branches SET bbalance = bbalance + 3758 WHERE  tuple          5
UPDATE pgbench_branches SET bbalance = bbalance + 1458 WHERE  None           4
END;                                                          None           4
END;                                                          XactSync       4
UPDATE pgbench_branches SET bbalance = bbalance + 3758 WHERE  None           2
UPDATE pgbench_branches SET bbalance = bbalance + 27 WHERE b  XactSync       2
UPDATE pgbench_branches SET bbalance = bbalance + 3758 WHERE  XactSync       2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can schedule this job to run every minute and output the results to a file if you need to preserve a history of AAS, top wait events, and top SQL queries. 

Implementation Notes 

Previously, this feature required the user to have write privileges because it used temporary tables. I have updated the implementation to eliminate the dependency on temporary tables, instead using a Pandas DataFrame to process the data in memory. This allows the tool to run successfully even on read-only databases. 

Important Considerations 

Please note that because sampling occurs every second, short-lived queries (executing in the millisecond range) may be missed. An Average Active Session count of zero does not necessarily mean no queries were executed during the minute. For a more comprehensive view of executed queries, consider sampling pg_stat_statements using the pgcheck -psss option.

pg_stat_activity sampling is best used to understand the general workload and overall database health.


Summary 

The new -psas option in pgcheck provides a lightweight, real-time snapshot of PostgreSQL activity by sampling pg_stat_activity every second for one minute. This tool helps identify Average Active Sessions and top wait events, serving as a helpful diagnostic resource. By moving to in-memory processing with Pandas, this feature is now compatible with read-only database connections, making it more flexible for troubleshooting performance issues.

Monday, June 16, 2025

SnowSQL config password needs to be enclosed in double quotes

Today I tested how to use snowsql to connect to SnowFlake. I put the connection credential in the config file. But I encountered the following error message in the intial attempt:



(venv) c:\Users\Yu\.snowsql>snowsql

250001 (08001): Failed to connect to DB: abcdefg-hij01234.snowflakecomputing.com:443. Incorrect username or password was specified.

If the error message is unclear, enable logging using -o log_level=DEBUG and see the log to find out the cause. Contact support for further help.

Goodbye!



It turned out I need to enclose the password with double quotes in the config file.


for example, in the c:\Users\Yu\.snowsql\.config file:


accountname =abcdefg-hij01234

username =denissun

# password =Ab0cdE725##FG0 -- not working

password = "Ab0cdE725##FG0"  -- works!



After put double quotes, I tested again and it succeeded:


(venv) c:\Users\Yu\.snowsql>snowsql

* SnowSQL * v1.4.1

Type SQL statements or !help

denissun9883#COMPUTE_WH@(no database).(no schema)>!help

+------------+-------------------------------------------+-------------+--------------------------------------------------------------------------------------------+

| Command  | Use                    | Aliases   | Description                                        |

|------------+-------------------------------------------+-------------+--------------------------------------------------------------------------------------------|

| !abort   | !abort <query id>             |       | Abort a query                                       |

| !connect  | !connect <connection_name>        |       | Create a new connection                                  |

| !define  | !define <variable>=<value>        |       | Define a variable as the given value                            |

| !edit   | !edit <query>               |       | Opens up a text editor. Useful for writing longer queries. Defaults to last query     |

| !exit   | !exit                   | !disconnect | Drop the current connection                                |

| !help   | !help                   | !helps, !h | Show the client help.                                   |

| !options  | !options                 | !opts    | Show all options and their values                             |

| !pause   | !pause                  |       | Pauses running queries.                                  |

| !print   | !print <message>             |       | Print given text                                      |

| !queries  | !queries help, <filter>=<value>, <filter> |       | Lists queries matching the specified filters. Write <!queries> help for a list of filters. |

| !quit   | !quit                   | !q     | Drop all connections and quit SnowSQL                           |

| !rehash  | !rehash                  |       | Refresh autocompletion                                   |

| !result  | !result <query id>            |       | See the result of a query                                 |

| !set    | !set <option>=<value>           |       | Set an option to the given value                              |

| !source  | !source <filename>, <url>         | !load    | Execute given sql file                                   |

| !spool   | !spool <filename>, off          |       | Turn on or off writing results to file                           |

| !system  | !system <system command>         |       | Run a system command in the shell                             |

| !variables | !variables                | !vars    | Show all variables and their values                            |

+------------+-------------------------------------------+-------------+--------------------------------------------------------------------------------------------+



It could be due to my password has special characters. 


From Blogger iPhone client